Custom Media formatter

for byte[]

send a file into stream (byte[]) and get uploaded into other solution.

Add new class to web api service

public class BinaryMediaTypeFormatter : MediaTypeFormatter
{

private static Type _supportedType = typeof(byte[]);
private const int BufferSize = 8192; // 8K

public BinaryMediaTypeFormatter()
{
SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue(“application/octet-stream”));
}

public override bool CanReadType(Type type)
{
return type == _supportedType;
}

public override bool CanWriteType(Type type)
{
return type == _supportedType;
}

public override Task<object> ReadFromStreamAsync(Type type, Stream stream,
HttpContent contentHeaders, IFormatterLogger formatterLogger)
{
var taskSource = new TaskCompletionSource<object>();
try
{
var ms = new MemoryStream();
stream.CopyTo(ms, BufferSize);
taskSource.SetResult(ms.ToArray());
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}

public override Task WriteToStreamAsync(Type type, object value, Stream stream,
HttpContent contentHeaders, TransportContext transportContext)
{
var taskSource = new TaskCompletionSource<object>();
try
{
if (value == null)
value = new byte[0];
var ms = new MemoryStream((byte[])value);
ms.CopyTo(stream);
taskSource.SetResult(null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
}

controller code

// POST api/values
public void Post(Byte[] data)
{
try
{
// instance a memory stream and pass the
// byte array to its constructor
MemoryStream ms = new MemoryStream(data);

// instance a filestream pointing to the
// storage folder, use the original file name
// to name the resulting file
FileStream fs = new FileStream
(System.Web.Hosting.HostingEnvironment.MapPath(“~/App_Data/”) +
“test.dll”, FileMode.Create);

// write the memory stream containing the original
// file as a byte array to the filestream
ms.WriteTo(fs);

// clean up
ms.Close();
fs.Close();
fs.Dispose();

// return OK if we made it this far

}
catch (Exception ex)
{
// return the error message if the operation fails

}
}

 

Client code

private void UploadFile(string filename)
{
try
{
// get the exact file name from the path
String strFile = System.IO.Path.GetFileName(filename);

// create an instance fo the web service
//TestUploader.Uploader.FileUploader srv = new TestUploader.Uploader.FileUploader();

// get the file information form the selected file
FileInfo fInfo = new FileInfo(filename);

// get the length of the file to see if it is possible
// to upload it (with the standard 4 MB limit)
long numBytes = fInfo.Length;
double dLen = Convert.ToDouble(fInfo.Length / 1000000);

// Default limit of 4 MB on web server
// have to change the web.config to if
// you want to allow larger uploads
if (dLen < 4)
{
// set up a file stream and binary reader for the
// selected file
FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);

// convert the file to a byte array
byte[] data = br.ReadBytes((int)numBytes);

var jsonStr = new ByteArrayContent(data);

br.Close();

// pass the byte array (file) and file name to the web service
// string sTmp = srv.UploadFile(data, strFile);

//////////////

var restClient = new RestClient(“http://localhost:63045/&#8221;);
restClient.AddHandler(“application/octet-stream”, new RestSharp.Deserializers.JsonDeserializer());
var request = new RestRequest(“api/values”,Method.POST);
request.AddHeader(“Content-Type”, “application/octet-stream”);

request.AddParameter(“application/octet-stream”, data, ParameterType.RequestBody);
var response = restClient.Execute(request);
////////////////
fStream.Close();
fStream.Dispose();

// this will always say OK unless an error occurs,
// if an error occurs, the service returns the error message
//MessageBox.Show(“File Upload Status: ” + sTmp, “File Upload”);
}
else
{
// Display message if the file was too large to upload
MessageBox.Show(“The file selected exceeds the size limit for uploads.”, “File Size”);
}
}
catch (Exception ex)
{
// display an error message to the user
MessageBox.Show(ex.Message.ToString(), “Upload Error”);
}
}

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s