I'm trying to save (an) uploaded file(s) to a database/memorystream, but I can't figure it out.
All I have right now is this:
public Task<HttpResponseMessage> AnswerQuestion()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
foreach (var file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
But of course this only saves the file to a specific location. I think I have to work with a custom class derived from MediaTypeFormatter to save it to a MemoryStream, but I don't see how to do it.
Please help. Thanks in advance!
You can use MultipartMemoryStreamProvider for your scenario.
[Updated] Noticed that you are using RC, i think MultipartMemoryStreamProvider was added post-RC and is currently in RTM.
Multipart content can be read into any of the concrete implementations of the abstract MultipartStreamProvider
class - see http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/8fda60945d49#src%2fSystem.Net.Http.Formatting%2fMultipartStreamProvider.cs.
These are:
- MultipartMemoryStreamProvider
- MultipartFileStreamProvider
- MultipartFormDataStreamProvider
- MultipartRelatedStreamProvider
In your case:
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new MultipartMemoryStreamProvider();
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
foreach (var item in streamProvider.Contents)
{
//do something
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With