I want to upload a file asynchronously from a web page to an ASP.NET MVC action:
[HttpPost]
public JsonResult AnalyseFile(HttpPostedFileBase file)
{
// do stuff
return Json(someResultObjects);
}
My problem is that when the method executes on the server, the file argument is null.
Over in HTML land, I have an input field containing a file:
<input type="file" accept=".xlsx" required="required" id="FileInput" name="FileInput" onchange="javascript:AnalyseFile();" />
And I have some javascript code:
function AnalyseFile() {
var fileInput = document.getElementById('FileInput');
var file = fileInput.files[0];
var url = 'http://someserver/somecontroller/AnalyseFile';
var xhr = new XMLHttpRequest();
xhr.upload.onreadystatechange = function() {
if(xhr.readyState == 4) {
// do stuff
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('file=' + file);
}
I've verified that the javascript file object has a reference to the file by inserting the following line of code after var file = fileInput.files[0]:
alert(file.Name);
which correctly displays the file name in a message box.
However, when the server side method is called, the file itself is missing (the HttpPostedFileBase "file" argument is null). Can anyone advise me what I'm doing wrong here? The objective is for the HttpPostedFileBase to have the reference to the file so I can do some analyses on it on the server and send the results back to the browser for rendering to the user.