and tie...">

ASP.NET MVC 3: Support for loading multiple HTML5 files?

Can i use:

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

and tie it to:

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

I am writing a web application for modern browsers and should not worry about IE, so I would like to avoid using Flash. Right now, files always empty when I submit a form. Is there a way to make this work in MVC 3?

Thanks!

+6
source share
4 answers

Do you have the encoding configured in your form correctly?

I believe that you still need to:

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

In the form declaration so that the browser can publish files.

For instance:

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

Is it possible to use 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"); } 
+1
source

My index:

  @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 the controller

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

And files contain downloaded files - works great for me!

0
source

This will not work:

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

Should do the following:

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

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


All Articles