Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 630
Jeff Camera Avatar asked Jan 09 '12 00:01

Jeff Camera


2 Answers

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" }))
like image 92
Gats Avatar answered Oct 24 '22 12:10

Gats


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");
}
like image 26
ron tornambe Avatar answered Oct 24 '22 10:10

ron tornambe