本篇體驗上傳多個文件。兄弟篇為:
MVC文件上傳01-使用jquery異步上傳並客戶端驗證類型和大小
MVC最基本上傳文件方式中的一個遺漏點
□ 前台視圖部分
1: <% using(Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new {enctype = "multipart/form-data"}) {)%>
2: <input name ="uploadFile" type="file" />
3: <input type="submit" value="Upload File" />
4: <%}%>
□ 控制器部分
1: [HttpMethod.Post]
2: public ActionResult FileUpload(HttpPostedFileBase uploadFile)
3: {
4: if(uploadFile.ContenctLength > 0)
5: {
6: //獲得保存路徑
7: string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
8: Path.GetFileName(uploadFile.FileName));
9: uploadFile.SaveAs(filePath);
10: }
11: return View();
12: }
以上的問題是:當沒有文件上傳的時候,會報錯。需要判斷HttpPostedFileBase實例是否為null
1: [HttpMethod.Post]
2: public ActionResult FileUpload(HttpPostedFileBase uploadFile)
3: {
4: if(uploadFile != null)
5: {
6: if(uploadFile.ContenctLength > 0)
7: {
8: //獲得保存路徑
9: string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
10: Path.GetFileName(uploadFile.FileName));
11: uploadFile.SaveAs(filePath);
12: }
13: }
14: return View();
15: }
上傳多個文件
□ 控制器
● 由於接收多個文件,所以控制器方法的參數變成了IEnumerable<HttpPostedFileBase> files
● 變量files與前台視圖的name屬性值對應
● 如果沒有指定的文件夾,就創建一個文件夾
1: using System;
2: using System.Collections.Generic;
3: using System.IO;
4: using System.Linq;
5: using System.Web;
6: using System.Web.Mvc;
7:
8: namespace MvcApplication2.Controllers
9: {
10: public class HomeController : Controller
11: {
12: public ActionResult Index()
13: {
14: return View();
15: }
16:
17: public ActionResult MultiUpload(IEnumerable<HttpPostedFileBase> files)
18: {
19: string pathForSaving = Server.MapPath("~/Uploads");
20: if (this.CreateFolderIfNeeded(pathForSaving))
21: {
22: foreach (var file in files)
23: {
24: if (file != null && file.ContentLength > 0)
25: {
26: var path = Path.Combine(pathForSaving, file.FileName);
27: file.SaveAs(path);
28: }
29: }
30: }
31:
32: return RedirectToAction("Index");
33: }
34:
35: // 檢查是否要創建上傳文件夾
36: private bool CreateFolderIfNeeded(string path)
37: {
38: bool result = true;
39: if (!Directory.Exists(path))
40: {
41: try
42: {
43: Directory.CreateDirectory(path);
44: }
45: catch (Exception)
46: {
47: //TODO:處理異常
48: result = false;
49: }
50: }
51: return result;
52: }
53: }
54: }
55:
□ Home/Index.cshtml視圖
1: @{
2: ViewBag.Title = "Index";
3: Layout = "~/Views/Shared/_Layout.cshtml";
4: }
5:
6: @using (Html.BeginForm("MultiUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
7: {
8: <input type="file" name="files" id="file1" /><br/>
9: <input type="file" name="files" id="file2" /><br/>
10: <input type="file" name="files" id="file3" /><br/>
11: <input type="submit" value="同時上傳多個文件" />
12: }
注意:name屬性值與控制器方法參數對應。
□ 結果
選擇上傳2個文件:
上傳成功后,自動創建了文件夾Uploads:
Uploads中只有2個文件:
□ 為什么使用HttpPostedFileBase而不是FormCollection來接收文件
public sealed class FormCollection : NameValueCollection, IValueProvider
可見,FormCollection是鍵值集合,鍵是string類型,值是string類型,而上傳的文件類型不是string,所以不能用FormCollection作為參數來接收文件。
參考資料