WebAPI File Uploading – Without writing files to disk

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x