WebAPI File Uploading - Without writing files to disk

41,993

Solved:

Use the existing simple MultipartMemoryStreamProvider. No custom classes or providers required. This differers from the duplicate question which solved the solution by writing a custom provider.

Then use it in a WebAPI handler as so:

public async Task<IHttpActionResult> UploadFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return StatusCode(HttpStatusCode.UnsupportedMediaType);
    }        
  
    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();
    
    foreach (var stream in filesReadToProvider.Contents)
    {
        var fileBytes = await stream.ReadAsByteArrayAsync();
    }
    return StatusCode(HttpStatusCode.OK);
}
Share:
41,993

Related videos on Youtube

simbolo
Author by

simbolo

Everything From CRM, CMS, eCommerce and business applications from desktop, web and mobile. Strictly web applications only. Special interest in security and privacy.

Updated on June 24, 2020

Comments

  • simbolo
    simbolo almost 4 years

    All the documentation / tutorials / questions about processing a file uploaded using FormData to a ASP.NET WebAPI handler use MultipartFormDataStreamProvider to process the multipart stream to split it into the relevant form fields and files.

    var root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);
    
    await Request.Content.ReadAsMultipartAsync(provider);
    
    foreach (MultipartFileData file in provider.FileData)
    {
       // File
    }
    

    However, the files are automatically written to a directory during processsing.

    It seems a lot of hassle when I could just use HttpContext.Current.Request.Files[0].InputStream to access a given file stream directly in memory.

    How can WebAPI just access the file stream directly without the IO overhead of using MultipartFormDataStreamProvider?

    Official tutorial: http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2

    • Jon Susiak
      Jon Susiak over 9 years
      I think This Question should answer your needs.
    • simbolo
      simbolo over 9 years
      Thanks @JonSusiak - I wish I found that a few hours ago, I ended up doing the exact same thing by examining the source code or MultipartFormDataStreamProvider and using the MultipartStreamProvider provider to give me the file upload in a MemoryStream rather than writing it to disk. Was just getting round to posting the answer.
    • Merenzo
      Merenzo over 7 years
      @simbolo - why didn't you use HttpContext.Current.Request.Files[0].InputStream? Could you explain the disadvantage?
    • xdiegom
      xdiegom about 6 years
      Microsoft has a really good example for how to upload files: docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/…
  • guiomie
    guiomie almost 9 years
    Where can I find IHttpActionResult ?
  • simbolo
    simbolo almost 9 years
    @guiomie simple google: msdn.microsoft.com/en-us/library/…
  • mbx-mbx
    mbx-mbx over 6 years
    Could this code please be updated so that it compiles? Not all code paths return a value. Thanks.
  • George Harnwell
    George Harnwell over 6 years
    @Magrangs - you simply need to return a Http Result such as return Ok();
  • Henrik Høyer
    Henrik Høyer over 6 years
    end the method with: return Request.CreateResponse(HttpStatusCode.OK);
  • Unbreakable
    Unbreakable over 5 years
    Can I simply send even big files to this function, or I need to define some boundary and other fancy stuff in the client side which sends the file?
  • A X
    A X over 4 years
    This doesn't work though - it gets screwed up from an encoding perspective
  • David
    David over 4 years
    With asp.net 4.7 I am still getting exception Exception. Exception type full name: System.NullReferenceException.] - [System.NullReferenceException: Object reference not set to an instance of an object
  • Brett JB
    Brett JB over 4 years
    Hi @simbolo, I am also wanting to do this and have managed to extract the file data using your approach. I also have additional form data as well though. Do you have any ideas how I can get to that? The filestoreadprovider is a collection of HttpContent objects, which I have managed to make into a list and walk through, but I cant seem to get at the data. Any Ideas? (Before I throw this out as seperate question..) Thanks...
  • Brent Woodle
    Brent Woodle over 4 years
    The MultipartMemoryStreamProvider doesn't have an API for accessing form data that is included in the request like MultipartFormDataStreamProvider.FormData does.