文件上傳簡單實現是很是容易的,可是想要更高的要求,好比經過ajax上傳文件、一次上傳多個文件、文件比較大等等,這裏面的坑就不是很容易填(對於新手來講)。所以在這裏我準備經過ajax實現多文件上傳。在開始貼代碼以前,要注意幾點:html
1.<input type="file" />是必需要加name的,不知道爲何不加name屬性,後臺獲取不到文件數據(有辦法的大神能夠在評論區提醒我),而後是multiple屬性,當multiple="multiple"時,file控件是能夠多選須要上傳的文件的(<input type="file" multiple="multiple" name="myFile" />)。web
2.form要設enctype爲multiple/form-data,multipart/form-data表示:不對字符編碼,在使用包含文件上傳控件的表單時,必須使用該值。關於enctype的詳細講解能夠查看http://www.jb51.net/web/165444.htmlajax
3.重點來了,ajax的參數設置裏面有大坑(不少人都沒注意ajax的衆多參數),contentType和processData須要設爲false,contentType明明被要求爲string類型,可是這裏要設爲false(我也不知道爲何),網上關於contentType的說明大可能是"contentType:要求爲String類型的參數,當發送信息至服務器時,內容編碼類型默認爲"application/x-www-form-urlencoded"。該默認值適合大多數應用場合",還有個data要設爲new FormData($(' ')[0]),想了解其餘參數的可看這個http://www.cnblogs.com/babietongtianta/p/4543170.html。服務器
下面就是簡單的前臺代碼:app
<form id="uploadForm" enctype="multipart/form-data" action="/Login/uploadFile" method="post"> <input type="file" multiple="multiple" id="PersonFile" name="MyFile" /> <button type="button" id="submitFile" onclick="uploadFile()">提交</button> </form>
//上傳文件 function uploadFile() { debugger $.ajax({ url: '/Login/uploadFile', type: 'POST', cache: false, data: new FormData($('#uploadForm')[0]), processData: false, // 關鍵點 contentType: false, // 關鍵點 success: function (result) { if (result.Check) { alert("成功"); } else { alert("失敗"); } var file = $("#PersonFile") file.after(file.clone().val("")); file.remove(); } }); }
如今輪到後臺了,我這邊後臺是經過System.Web.HttpContext.Current.Request.Files獲取文件數據集的,以後的代碼我將以圖片爲例。asp.net
[HttpPost] public ActionResult uploadFile() { Result<string> check = new Result<string>(); try { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; int number = 0; for (int i = 0; i < files.Count; i++) { System.Text.StringBuilder fileName = new System.Text.StringBuilder(); fileName.Append(@"D:\"); fileName.Append(DateTime.Now.ToString("yyMMdd")); fileName.Append(@"\"); if (!System.IO.Directory.Exists(fileName.ToString())) { System.IO.Directory.CreateDirectory(fileName.ToString()); } fileName.Append(System.IO.Path.GetFileNameWithoutExtension(files[i].FileName)); fileName.Append(DateTime.Now.ToString("yyMMddHHmmss")); fileName.Append(System.IO.Path.GetExtension(files[i].FileName)); System.IO.Stream sm = files[i].InputStream; if (System.IO.File.Exists(@"D:\水印log.jpg")) { ImageHelper.ZoomAuto(sm, fileName.ToString(), 400, 300, "", @"D:\水印log.jpg"); } else { ImageHelper.ZoomAuto(sm, fileName.ToString(), 400, 300, "水印LOG", ""); } bool ok = System.IO.File.Exists(fileName.ToString()); if (ok) { number++; } } if (number.Equals(files.Count)) { check.Message = "上傳成功!"; check.Check = true; } else { check.Message = "失敗!"; check.Check = false; } return Json(check); } catch(Exception ex) { check.Message = ex.ToString(); check.Check = false; return Json(check); } }
/// <summary> /// 返回值 /// </summary> public class Result<T> { public string Message { get; set; } public bool Check { get; set; } public IList<T> ResultList { get; set; } }
其中用到了ImageHelper.ZoomAuto(),這個是吳劍大哥寫的圖片處理類,地址http://www.cnblogs.com/wu-jian/archive/2011/02/21/1959382.html。最後還有一個坑,就是asp.net對一次上傳數據的大小是有限制的,要解除限制才能10個20個文件同時上傳。如何解除限制?在web.config裏面配置一下就OK了。代碼以下:post
<system.web> <authentication mode="None" /> <compilation debug="true" targetFramework="4.5" /> <!--<httpRuntime targetFramework="4.5" />--> <httpRuntime executionTimeout="500" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" /> </system.web>
把<httpRuntime >放<system.web>節點下。ui