我发现了以下很棒的主题,并解释了如何使用新的HTML5 FormDataAPI通过AJAX / Jquery上传文件
这是该代码的稍有更新的版本,具有更新的JQuery 1.8+语法
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: '/Upload', //my ASP.NET MVC method
type: 'POST',
// handle the progress report
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
})
.done(function(){
alert("success");
})
.fail(function(){
alert("error");
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
这是表格
在服务器端,我们有类似的东西。
[HttpPost]
public string Upload(HttpPostedFileBase file)
{
// do something with file
return "you uploaded a file called " + file.FileName;
}
这很好。直到您决定在文件对话框中使用“多个”属性,然后发送多个文件。
您会在网上找到各种页面,提出以下解决方案
public string Upload(IEnumerable files)
{
foreach(var file in files)
...
}
哎呀。不起作用
public string Upload(List files)
{
foreach(var file in files)
...
}
不。不起作用
public string Upload(IEnumerable files)
{
foreach(var file in files)
...
}
甚至不 编译
public string Upload(HttpPostedFileBase[] files)
{
foreach(HttpPostedFileBase file in files)
...
}
你猜怎么了?不起作用 让我们尝试处理Request.Files。好的旧的可靠Request.Files。从未失败。
public string Upload()
{
foreach (HttpPostedFileBase uf in Request.Files)
...
}
剧透警报:它不起作用。
啊哈 得到它了!我将遍历Request.Files中的键。
public string Upload()
{
foreach(var key in Request.Files.AllKeys)
{
var file = Request.Files[key];
}
}
再一次,它不起作用。