ASP.NET How read a multipart form data in Web API?
This should help you get started:
var uploadPath = HostingEnvironment.MapPath("/") + @"/Uploads";
Directory.CreateDirectory(uploadPath);
var provider = new MultipartFormDataStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(provider);
// Files
//
foreach (MultipartFileData file in provider.FileData)
{
Debug.WriteLine(file.Headers.ContentDisposition.FileName);
Debug.WriteLine("File path: " + file.LocalFileName);
}
// Form data
//
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Debug.WriteLine(string.Format("{0}: {1}", key, val));
}
}
This is code i've used before to receive json data + an optional file:
var result = await Request.Content.ReadAsMultipartAsync();
var requestJson = await result.Contents[0].ReadAsStringAsync();
var request = JsonConvert.DeserializeObject<MyRequestType>(requestJson);
if (result.Contents.Count > 1)
{
var fileByteArray = await result.Contents[1].ReadAsByteArrayAsync();
...
}
Its really neat that you can combine different types of data in a request like this.
Edit: an example of how to send this request:
let serialisedJson = JSON.stringify(anyObject);
let formData = new FormData();
formData.append('initializationData', serialisedJson);
// fileObject is an instance of File
if (fileObject) {
// the 'jsonFile' name might cause some confusion:
// in this case, the uploaded file is actually a textfile containing json data
formData.append('jsonFile', fileObject);
}
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://somewhere.com', true);
xhr.onload = function(e: any) {
if (e.target.status === 200) {
resolve(JSON.parse(e.target.response));
}
else {
reject(JSON.parse(e.target.response));
}
};
xhr.send(formData);
});
You can read content and get all file information (in my example image) without copying to local disk in this way:
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)
{
// Getting of content as byte[], picture name and picture type
var fileBytes = await stream.ReadAsByteArrayAsync();
var pictureName = stream.Headers.ContentDisposition.FileName;
var contentType = stream.Headers.ContentType.MediaType;
}
}