Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Multipart/Form-Data without touching disk

Alright, so I want to receive a Multipart/Form-Data POST request in my WebAPI, and do things with the files and form fields contained within. That's easy, like so:

var provider = new MultipartFormDataStreamProvider(Path.GetTempPath());

await Request.Content.ReadAsMultipartAsync(provider);

var formValue = provider.FormData["form_value_here"];

var files = provider.FileData.Select(d => d.LocalFileName);

It's easy to get any form field or particular file I need. However, I would like to have similar capability, but instead of saving files to disk when ReadAsMultipartAsync is called, I'd like to have them in a Stream

The reasoning for this, is that I would like to hash the values of the file(s) being posted, and reject the request if necessary, before saving the files to disk. Is there built in provider or class that I've missed that has a convenient API?

like image 726
Ron Brogan Avatar asked Feb 01 '26 10:02

Ron Brogan


1 Answers

You can use MultipartMemoryStreamProvider to get the form data as a stream. You'll want something like this:

if (!Request.Content.IsMimeMultipartContent())
    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var fileNames = new List<string>();
foreach (var file in provider.Contents)
{
    fileNames.Add(file.Headers.ContentDisposition.FileName.Trim('\"'));
    var buffer = await file.ReadAsByteArrayAsync();
    //hash values, reject request if needed
}

return Ok();
like image 123
Andrew M. Avatar answered Feb 02 '26 23:02

Andrew M.