Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 439
simbolo Avatar asked Jan 15 '15 14:01

simbolo


People also ask

How do I upload files to IFormFile?

Upload Single FileTo add view, right click on action method and click on add view. Then select View from left side filter and select Razor View – Empty. Then click on Add button. Create design for your view as per your requirements.


1 Answers

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); } 
like image 181
simbolo Avatar answered Oct 14 '22 09:10

simbolo