Upload multiple files using HttpFileCollectionBase issue with C # and MVC3

I created a controller that saves files.

The following code is part of this controller:

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" ); } } } } 

on an aspx page is simple:

 <input type="file" name="file" /> <input type="file" name="file" /> ...// many inputs type file 

The problem is foreach because it returns an error (I know, because I run in debug mode and set a breakpoint in the foreach statement):

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

What's my mistake?

+4
source share
3 answers

Try it like this:

 [HttpPost] public ActionResult Upload(IEnumerable<HttpPostedFileBase> 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"); } 

and change the markup so that the file entries are called files:

 <input type="file" name="files" /> <input type="file" name="files" /> ...// many inputs type file 
+10
source
 for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; // this file Type is HttpPostedFileBase which is in memory } 

HttpRequestBase.Files requires an index, so use for instead of foreach .

+3
source

Check out this post by Phil Haack, which demonstrates how to handle multiple file downloads using MVC. The object you are trying to use is for ASP.NET web forms.

+2
source

Source: https://habr.com/ru/post/1399020/


All Articles