Jeff Camera
Jeff Camera

Reputation: 5544

ASP.NET MVC 3: Support for HTML5 multiple file upload?

Can I use:

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

and bind it to:

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

I'm writing a web app for modern browsers and don't have to worry about IE so I'd like to avoid using Flash. Right now files is always null when I post the form. Is there any way to get this to work in MVC 3?

Thanks!

Upvotes: 6

Views: 6683

Answers (4)

Minh Nguyen
Minh Nguyen

Reputation: 2201

This won't work:

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

Should do like this:

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

Upvotes: 0

ron tornambe
ron tornambe

Reputation: 10780

Wouldn't one use the Request.Files for backward compatibility as follows:

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

Upvotes: 1

DrAlligieri
DrAlligieri

Reputation: 211

My Index View:

    @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" />
}   

In controller

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

And files contains uploaded files - works fine for me!

Upvotes: 0

Gats
Gats

Reputation: 3462

Do you have your encoding set correctly in your form?

I believe you still need:

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

In the form declaration to ensure the browser can post files.

For example:

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

Upvotes: 13

Related Questions