根據(jù)項目需要,研究了一下如何在ASP.NETMVC下實現(xiàn)批量文件上傳。首先,介紹單文件上傳;然后,介紹多文件上傳如何實現(xiàn)。
一、單文件上傳
單文件上傳的原理是將文件數(shù)據(jù)放入request中,由頁面直接傳遞至后臺controller中,類似于view和controller之間傳參數(shù),直接貼上代碼加注釋。
Upload.aspx文件中的代碼:
<form enctype="multipart/form-data" method="post"> <input type="file" id="file" /> <input type="submit" value="上傳" /></form>
Controller中代碼:
[HttpPost]public ActionResult Upload(FormCollection form){ if (Request.Files.Count == 0){ //Request.Files.Count 文件數(shù)為0上傳不成功 return View(); } var file = Request.Files[0]; if (file.ContentLength == 0){ //文件大小大(以字節(jié)為單位)為0時,做一些操作 return View(); } else{ //文件大小不為0 file = Request.Files[0]; //服務(wù)器上的UpLoadFile文件夾必須有讀寫權(quán)限 string target = Server.MapPath("/")+("/Mock/Learning/");//取得目標(biāo)文件夾的路徑 string filename = file.FileName;//取得文件名字 string path = target + filename;//獲取存儲的目標(biāo)地址 file.SaveAs(path);} return View();}這里需要注意的是,在ASP.NET中,request的默認(rèn)大小為4M,因此,如需上傳較大文件,需要更改Web.config。
<system.web> <httpRuntime maxRequestLength="40960"/> </system.web>
二、批量文件上傳
思路是通過js根據(jù)用戶需求動態(tài)添加上傳控件,多個文件通過request一并上傳至controller。
Upload.aspx文件中的代碼:
<form enctype="multipart/form-data" method="post"> <div id="FileList"> <div> <input type="file" id="file" name="file0"/> </div> </div> <p> <a onclick="AddFile();">添加文件</a> </p> <p> <input type="submit" value="上傳" /> </p></form><script>var index = 1; function AddFile() { var ul = document.getElementById("FileList"); var inputDiv = document.createElement("div"); inputDiv.setAttribute("Id", "div" + index); var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("id", "file" + index); file.setAttribute("name", "file" + index); var btnDel = document.createElement("input"); btnDel.setAttribute("type", "button"); btnDel.setAttribute("value", "刪除"); btnDel.setAttribute("Id", index); btnDel.onclick = function() { inputDiv.removeChild(file); inputDiv.removeChild(btnDel); ul.removeChild(inputDiv); } inputDiv.appendChild(file); inputDiv.appendChild(btnDel); ul.appendChild(inputDiv); index++;}</script>Controller中的代碼:
新聞熱點
疑難解答
圖片精選