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
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.
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); } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With