我发现
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; }
这很好. UNTIL您决定在文件对话框中使用“multiple”属性,并发送多个文件.
<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. Good老可靠Request.Files.从未失败.
public string Upload() { foreach (HttpPostedFileBase uf in Request.Files) ... }
Spoiler警报:它不起作用
啊哈.得到它了!我将在Request.Files中迭代键.
public string Upload() { foreach(var key in Request.Files.AllKeys) { var file = Request.Files[key]; } }
再一次,它不行.