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?
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();
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