我想從一個網頁異步上傳文件的ASP.NET MVC行動:上傳文件異步地MVC.NET
[HttpPost]
public JsonResult AnalyseFile(HttpPostedFileBase file)
{
// do stuff
return Json(someResultObjects);
}
我的問題是,當該方法在服務器上執行時,文件參數爲空。
在HTML中的土地,我有一個包含文件輸入字段:
<input type="file" accept=".xlsx" required="required" id="FileInput" name="FileInput" onchange="javascript:AnalyseFile();" />
而且我有一些JavaScript代碼:
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);
}
我驗證過javascript文件對象有一個通過在var file = fileInput.files [0]之後插入以下代碼行來引用文件:
alert(file.Name);
正確顯示消息框中的文件名稱。
但是,當調用服務器端方法時,文件本身缺失(HttpPostedFileBase「文件」參數爲空)。任何人都可以告訴我我在這裏做錯了什麼?目標是讓HttpPostedFileBase具有對文件的引用,以便我可以在服務器上對它進行一些分析,並將結果發送回瀏覽器以便呈現給用戶。
不應該輸入名稱是否等於HttpPostetFileBase名稱,即「文件」? – andreasnico
服務器是否期待'javascript''File'對象?在'公共JsonResult AnalyseFile(HttpPostedFileBase文件)''JSONResult'表示服務器在'POST'處期待'JSON'嗎? – guest271314
查看http://stackoverflow.com/questions/19042116/ajax-beginform-in-mvc-to-upload-files/ – guest271314