Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .Net Web API RC: Multipart file-upload to Memorystream

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!

like image 849
jurgen_be Avatar asked Aug 30 '12 11:08

jurgen_be


2 Answers

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.

like image 26
Kiran Avatar answered Sep 23 '22 02:09

Kiran


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
       }
   });
}
like image 59
Filip W Avatar answered Sep 25 '22 02:09

Filip W