4

I created a controller which save files.

The below code is a part of that 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" );
               }
            }
         }
 }

in 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 like (I know because I run in Debug mode and placed breakpoint at foreach statement):

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

What is my mistake ?

3 Answers 3

11

Try 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 modify the markup so that the file inputs are named files:

<input type="file" name="files" />
<input type="file" name="files" />
...// many inputs type file
Sign up to request clarification or add additional context in comments.

3 Comments

I tried the above code (it seems with my code) but I changed my mind regarding to foreach. I'm using now the for statement. And it works good.
and the last mention: I have no parameters in my controller function
I tried this solution but I don't retrieve any value!
3
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 requires an index, so use for instead of foreach.

Comments

2

Have a look at this post by Phil Haack which demonstrates how to process multiple file uploads using MVC. The object you are trying to use is for ASP.NET Webforms.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.