使用C#和MVC3的HttpFileCollectionBase问题上传多个文件

我创建了一个保存文件的控制器。

以下代码是该控制器的一部分:

if ( Request.Files.Count != 0 ) { HttpFileCollectionBase files = Request.Files; foreach ( HttpPostedFileBase file in files ) { if ( file.ContentLength > 0 ) { if ( !file.ContentType.Equals( "image/vnd.dwg" ) ) { return RedirectToAction( "List" ); } } } } 

在ASPX页面很简单:

   ...// many inputs type file 

问题是foreach因为它返回一个错误(我知道因为我在调试模式下运行并在foreach语句中放置了断点):

 Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFileBase'. 

我的错是什么?

试试这样:

 [HttpPost] public ActionResult Upload(IEnumerable files) { if (files != null && files.Count() > 0) { foreach (var uploadedFile in files) { if (uploadedFile.ContentType != "image/vnd.dwg") { return RedirectToAction("List"); } var appData = Server.MapPath("~/app_data"); var filename = Path.Combine(appData, Path.GetFileName(uploadedFile.FileName)); uploadedFile.SaveAs(filename); } } return RedirectToAction("Success"); } 

并修改标记,以便文件输入是命名文件:

   ...// many inputs type file 
 for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; // this file's Type is HttpPostedFileBase which is in memory } 

HttpRequestBase.Files需要一个索引,因此使用而不是foreach

看看Phil Haack的这篇文章 ,它演示了如何使用MVC处理多个文件上传。 您尝试使用的对象是ASP.NET Webforms。