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
I think the answers here are excellent. So others can see a somewhat simple example of how to pass data in addition to the file in summary form, included is a Javascript Function that makes the WebAPI call to the FileUpload Controller, and the snippet from the FileUpload Controller (in VB.net) that reads the additional data passed from Javascript.
Javascript:
function uploadImage(files) {
var data = new FormData();
if (files.length > 0) {
data.append("UploadedImage", files[0]);
data.append("Source", "1")
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/fileupload/uploadfile",
contentType: false,
processData: false,
data: data
});
File Upload Controller:
_
Public Function UploadFile() As KeyValuePair(Of Boolean, String)
Try
If HttpContext.Current.Request.Files.AllKeys.Any() Then
Dim httpPostedFile = HttpContext.Current.Request.Files("UploadedImage")
Dim source = HttpContext.Current.Request.Form("Source").ToString()
So as you can see in the Javascript, the additional data passed is the "Source" key, and the value is "1". And as Chandrika has answered above, the Controller reads this passed data through "System.Web.HttpContext.Current.Request.Form("Source").ToString()".
Note that Form("Source") uses () (vs. []) as the controller code is in VB.net.
Hope this helps.