【发布时间】:2014-03-14 03:01:48
【问题描述】:
我找到了following great thread,其中解释了如何使用新的 HTML5 FormData API 通过 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});
}
}
这是表格
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
在服务器端,我们有这样的东西。
[HttpPost]
public string Upload(HttpPostedFileBase file)
{
// do something with file
return "you uploaded a file called " + file.FileName;
}
这很好用。直到您决定在文件对话框中使用“多个”属性,并发送多个文件。
<form enctype="multipart/form-data">
<input name="file" type="file" multiple="multiple" />
<input type="button" value="Upload" />
</form>
<progress></progress>
您会在网上找到各种建议以下解决方案的页面
public string Upload(IEnumerable<HttpPostedFileBase> files)
{
foreach(var file in files)
...
}
哎呀。没用
public string Upload(List<HttpPostedFileBase> 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];
}
}
再一次,它不起作用。
【问题讨论】:
标签: jquery asp.net ajax html file-upload