WellThisIsAkward WellThisIsAkward - 14 days ago 5
ASP.NET (C#) Question

InvalidCastexception upload multiple images

Hi everyone I am creating an application using MVC 5, with a code first database,The code below shows the code I am currently trying to use to upload multiple images but I get an InvalidCastexception when trying to cast 'System.String' to type 'System.Web.HttpPostedFileBase'.

Thanks for your time and any help with this issue is greatly appreciated.

Images Controller

// GET: Images/Upload
[HttpGet]
public ActionResult Upload()
{
return View();
}

// POST: Images/Upload
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
{

HttpFileCollectionBase files = Request.Files;
foreach (HttpPostedFileBase file in files)
{
int length = file.ContentLength;
string type = file.ContentType;
string filename = file.FileName;
}
return RedirectToAction("Upload");

}


upload view

@{Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Upload</title>
</head>
<body>
<form method="post" action="~/Images/Upload" id="form1" enctype="multipart/form-data">
@if (ViewData.Model != null)
{
foreach (var item in ViewData.Model)
{
<img src="/Images/@item["Path"]" alt="FileUpload Image" />
}
}

<input type="file" name="uploadFiles" id="FileUpload" multiple="multiple" />

<input type="submit" name="btnSubmit" value="Upload" id="btnSubmit" />
</form>
</body>
</html>

Answer

You can't do that

foreach (HttpPostedFileBase file in files)

because the enumerator of HttpFileCollection will return names of the files (string) but not HttpPostedFileBase so you will got InvalidCastexception

Use uploadFiles in the loop instead of HttpFileCollectionBase

public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
{
        foreach (var file in uploadFiles)
        {
            int length = file.ContentLength;
            string type = file.ContentType;
            string filename = file.FileName;
        }
        return RedirectToAction("Upload");
}

or use for and index:

HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
     int length = files[i].ContentLength;
    string type = files[i].ContentType;
    string filename = files[i].FileName;
}
Comments