ASP.NET MVC實現多檔案上傳
阿新 • • 發佈:2018-12-23
要實現ASP.NET MVC中的多檔案上傳,其實最關鍵的一步是要在input上定義multiple屬性,使之可以支援多檔案上傳。
其實有幾個比較重要的地方,form一定要申明enctype=“multipart/form-data”,其次是 <input type="file" multiple name="files"/>,表單要有name屬性。
好了,前臺寫好之後,我們就可以選擇上傳的時候一下子上傳多個檔案了。
接下來,我們編寫後臺程式碼:
在ASP.NET中,我們習慣將一些常量配置到Web.config檔案中,然後我們就可以通過讀取配置檔案訪問到,注意的是需要新增System.Configuration.dll
這是我獨自封裝的一個上傳的處理類,其引數就是檔案的mime型別(IIS中可以找到近乎所有的檔案的Mine,在C#中呼叫,其位於“System.Web.MimeMapping”)。public static Array FilesProcess(string fileType) { List<string> list = new List<string>(); var colletion = HttpContext.Current.Request.Files; string newFileName = string.Empty, fullPath = string.Empty; string vPath = System.Configuration.ConfigurationManager.AppSettings["UpLoadFilesPath"]; string phyPath = HttpContext.Current.Server.MapPath("/"); try { for (int i = 0; i < colletion.Count; i++) { HttpPostedFile file = colletion[i]; if (file.ContentType.StartsWith(fileType) == false || file.FileName == "" || file.ContentLength == 0) { throw new Exception("上傳的檔案不允許為空"); //使用者並沒有上傳圖片,什麼都不做 } else { if (!file.ContentType.StartsWith(fileType)) { throw new Exception("上傳檔案的格式不滿足要求"); } string fileName = file.FileName; string extName = Path.GetExtension(fileName); newFileName = Guid.NewGuid() + extName; fullPath = phyPath + vPath + newFileName; file.SaveAs(fullPath); list.Add(vPath + newFileName); } } } catch (Exception ex) { list.Clear(); } return list.ToArray(); }
至於為什麼要判斷filesName和ContentLength,當用戶並沒有上傳檔案的時候,其Count也不為零。我們使用Guid重新為檔案命名,防止檔案衝突,大家可以看出,我這個全部寫到了try-catch裡面去了,這樣其實是不好的,一旦內部發生異常,就是外界無法知道你內部到底發生了什麼,所以我們再過載一個方法:
public static Array FilesProcess(string fileType,out string Msg) { List<string> list = new List<string>(); var colletion = HttpContext.Current.Request.Files; string newFileName = string.Empty, fullPath = string.Empty; string vPath = System.Configuration.ConfigurationManager.AppSettings["UpLoadFilesPath"]; string phyPath = HttpContext.Current.Server.MapPath("/"); try { for (int i = 0; i < colletion.Count; i++) { HttpPostedFile file = colletion[i]; if (file.ContentType.StartsWith(fileType) == false || file.FileName == "" || file.ContentLength == 0) { throw new Exception("上傳的檔案不允許為空"); //使用者並沒有上傳圖片,什麼都不做 } else { if (!file.ContentType.StartsWith(fileType)) { throw new Exception("上傳檔案的格式不滿足要求"); } string fileName = file.FileName; string extName = Path.GetExtension(fileName); newFileName = Guid.NewGuid() + extName; fullPath = phyPath + vPath + newFileName; // file.SaveAs(fullPath); list.Add(vPath + newFileName); } } } catch (Exception ex) { list.Clear(); Msg = ex.Message; } Msg = "檔案上傳成功!"; return list.ToArray(); }
我才疏學淺,僅供大家參考,如有錯誤,敬請海涵。