I have a problem uploading files using jQuery Ajax and Web API. When I make a POST to my API, I am not getting uploaded files in my controller.
In my HTML I have several file inputs with class="file" like this:
<form id="edit" enctype="multipart/form-data">
<input class="file" type="file" name="field_custom_file" accept='image/*' />
<input class="file" type="file" name="field_custom_file" accept='image/*' />
<input class="file" type="file" name="field_custom_file" accept='image/*' />
</form>
In addittion, I have a button which executes a Javascript function:
function send() {
var files = $('.file')[0].files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '/api/tripgroups',
contentType: false,
processData: false,
data: data,
success: function (result) {
toastr.success('Trip Group was updated!');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
},
enctype: 'multipart/form-data',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
}
Finally, in my web api controller, if I try to access HttpContext.Current.Request.Files I get an empty collection, and if I try to access content like this:
var streamProvider = new MultipartFormDataStreamProvider("images");
await Request.Content.ReadAsMultipartAsync(streamProvider);
Then I get this error:
Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'. Parameter name: content
Thanks in advance.