I want to upload a file and send along with the file some additional information, let's say a string foo and an int bar.
How would I write a ASP.NET WebAPI controller method that receives a file upload, a string, and an int?
My JavaScript:
var fileInput = document.querySelector("#filePicker");
var formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("foo", "hello world!");
formData.append("bar", 42);
var options = {
url: "/api/foo/upload",
data: formData,
processData: false // Prevents JQuery from transforming the data into a query string
};
$.ajax(options);
My WebAPI controller can access the file like this:
public async Task<HttpResponseMessage> Upload()
{
var streamProvider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(streamProvider);
var fileStream = await streamProvider.Contents[0].ReadAsStreamAsync();
}
But it's not clear to me how I can get at my string and my int. I figure I can probably say streamProvider.Content[1], or whatever, but that feels super nasty.
What's the Right Way? to write a WebAPI action that accepts a file upload, a string, and an int?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…