I am trying to upload files using AJAX to ASP.NET. I have this Javascript:
var xhr = new XMLHttpRequest();
for (var i = 0; i < files.length; i++) {
xhr.open('post', '/File/Upload', true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
var formData = new FormData();
formData.append("_file", files[i]);
xhr.send(files[i]);
}
files is an Array()
Then I try to access the post file in C# code, but the value is always null. How can I resolve this issue?
// Method 1, Result: file = null
HttpPostedFileBase file = Request.Files["_file"];
// Method 2, Result: postedFile.Count = 0
HttpFileCollectionBase postedFile = Request.Files;
Assuming you have the following form containing the file input field:
you could try the following function:
Now on the server you should be able to retrieve the file using
Request.Files.