10

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!

2 Answers 2

28

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
       }
   });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does 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?
What would the //do something bit look like...?
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.