C# – WebAPI File Uploading – Without writing files to disk

asp.netasp.net-web-apicmultipartform-data

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

Best Answer

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);
}