How Can I Capture Uploaded Files From HTML 5 Multiple File Entry Elements

If I have an input element, for example:

<input type="file" multiple="multiple" name="file1" /> 

and select several files, the browser creates several files with the same element 'file1' name. This is similar to multiple list selection.

So, how can I capture this in ASP.NET using the Request.Files collection? The Request.Files.AllKeys collection displays all the files, but the key values ​​are the same. Request.Files returns a string for each key, but I can only get the first file using the key:

 var file = Request.Files["file1"]; 

This gives me the first file, but I cannot access the others also selected this way, since they do not have a unique name. The iteration also does not work, since Request.Files returns keys, not actual file entries.

How to capture these secondary files in ASP.NET?

+4
source share
3 answers

First, you are correct that all the keys of the Request.Files collection will be "file1" (or whatever the name of your input element is).

However, you can scroll through the collection by index and retrieve the file name of each download using the File Name property for each HttpPostedFileBase object.

Each object will also contain an InputStream, and when I debug it in Visual Studio, I can see from the Length property that the stream actually contains the contents of each image.

Example:

 [HttpPost] public ActionResult Upload() { for (int i = 0; i < Request.Files.Count; i++) { Console.WriteLine(Request.Files[i].FileName); Console.WriteLine(Request.Files[i].InputStream.Length); } return View(); } 

I think the ASP.NET team did not expect multi-file downloads. You could probably write an adapter class to convert Request.Files to a collection using the HttpPostedFileWrapper iterator, so you can use the for / each structure.

+5
source

I'm not sure if you are using MVC, but if so, try the following:

  [HttpPost] public ActionResult Upload(HttpPostedFileBase[] files) { // Stuff with files } 

Each file will have an InputStream property, which you can use to access the content.

In addition, you need to specify the enctype attribute:

 <form action="" method="POST" enctype="multipart/form-data"> 

Hope this helps. I used similar code to process files coming through this jQuery plugin to upload files .

0
source
 <input id="File1" type="file" runat="server" size="60" multiple="" /> in .cs file HttpFileCollection uploads = HttpContext.Current.Request.Files; for (int i = 0; i < uploads.Count; i++) { HttpPostedFile upload = uploads[i]; Response.Write(@"alert('"+upload.FileName+"');"); } 

I think this might work ...

0
source

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


All Articles