ASP .Net Web API RC: Multipart file-upload to Memorystream
Solution 1
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
}
});
}
Solution 2
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.
jurgen_be
Updated on June 04, 2022Comments
-
jurgen_be almost 2 years
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!
-
Taras Alenin over 11 yearsDoes it mean the contents of each part will be loaded into memory? If you have large files being uploaded would that mean you have to write your own
MultipartStreamProvider
implementation? -
simonlchilds almost 9 yearsWhat would the
//do something
bit look like...?