2012-01-09 32 views
6

我可以使用:ASP.NET MVC 3:支持HTML5多文件上傳?

<input type="file" name="files" id="files" multiple="multiple" /> 

並將其綁定到:

[HttpPost] 
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files) 
{ 
    ... 
} 

我在寫現代的瀏覽器的Web應用程序,並且不擔心IE瀏覽器,所以我想避免使用Flash。當我發佈表單時,files始終爲空。有沒有什麼辦法讓這個在MVC 3中工作?

謝謝!

+1

的可能重複[多文件上傳與HTML 5](http://stackoverflow.com/questions/8713802/multi-file-upload-with-html-5) – 2012-01-09 00:23:59

+1

您可能需要創建自定義模型聯編程序。 – Craig 2012-01-09 00:28:40

+0

或者使簽名'公衆ActionResult上傳(HttpPostedFileBase []文件)' – 2012-01-09 00:31:50

回答

13

你的表單中的編碼設置是否正確?

我相信你仍然需要:

new { enctype = "multipart/form-data" } 

在窗體聲明,以確保瀏覽器可以上傳文件。

例如:

@using (Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" })) 
+0

是的,我有正確的編碼設置。謝謝 – 2012-01-09 00:27:25

+0

好吧,說得太快。回到雙重檢查,我有一個類型-o那裏阻止文件發佈! – 2012-01-09 00:44:29

1

一個也不想要使用Request.Files的向後兼容性如下:

public ActionResult UploadFiles() 
{ 
    string UpoadedFilesFolder = "YourServerFolder"; 
    string fileName =""; 
    byte[] fileData=null; 
    foreach (HttpPostedFileBase uf in Request.Files) 
    { 
    HttpPostedFileBase UpoadedFile = uf; 
    if (uf.ContentLength > 0) 
    { 
     fileName = Path.GetFileName(UpoadedFile.FileName); 
     using (BinaryReader br = new BinaryReader(UpoadedFile.InputStream)) 
     { 
     fileData = br.ReadBytes((int)UpoadedFile.InputStream.Length); 
     } 
     using (FileStream fs = new FileStream(Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath(UpoadedFilesFolder), fi.FileName), FileMode.Create)) 
     { 
     fs.Write(fileData, 0, fileData.Length); 
     } 
    } 
    } 
    return Content("OK"); 
} 
0

我的索引視圖:

@using (Html.BeginForm("Upload","home", FormMethod.Post,new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="files" value=" " multiple="multiple" /> 
    <input type="submit" name="btUpload" value="Upload" /> 
} 

在控制器

public ActionResult Upload(HttpPostedFileBase[] files) 
     { 
      TempData["Message"] = files.Count(); 
      return RedirectToAction("Index"); 
     } 

和文件包含上傳的文件 - 適合我!

0

這是行不通的:

foreach (HttpPostedFileBase uf in Request.Files) 
{ 
    HttpPostedFileBase UpoadedFile = uf; 
} 

應該這樣做:

for (int i=0; i<Request.Files.Count; i++) 
{ 
    HttpPostedFileBase UpoadedFile = Request.Files[i]; 
}