Reputation: 17681
If I have an input element like this:
<input type="file" multiple="multiple" name="file1" />
and select multiple files, the browser creates multiple files with the same 'file1' name element. It's like a multiple selection of a listbox.
So how do I capture this in ASP.NET using the Request.Files collection? The Request.Files.AllKeys collection shows all files, but the key values are all the same. Request.Files returns strings for each key but I can only retrieve the first file using the key:
var file = Request.Files["file1"];
This gives me the first file, but I can't access the others also selected in this way since they don't have a unique name. Iteration also doesn't work since Request.Files only returns keys not the actual file entries.
How do I capture these secondary files in ASP.NET?
Upvotes: 4
Views: 2502
Reputation: 5
<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 will may work...
Upvotes: 0
Reputation: 32898
First, you're right that all keys of the Request.Files collection will be 'file1' (or whatever the name of your input element happens to be).
However you can loop through the collection by index, and retrieve the filename of each upload with the 'Filename' property of each HttpPostedFileBase object.
Each object will also contain an InputStream, and when I debug this in Visual Studio, I can see from the Length property that the stream actually contains the content 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 guess the ASP.NET team didn't anticipate multi-file uploads. You could probably write an adapter class to convert Request.Files to a collection with a HttpPostedFileWrapper iterator, so you can use a for/each structure.
Upvotes: 5
Reputation: 2226
I'm not sure if you're using MVC, but if so, try this:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files)
{
// Stuff with files
}
Each file will have an InputStream property you can use to get access to the contents.
Also, you'll need to specify the enctype attribute:
<form action="" method="POST" enctype="multipart/form-data">
Hope this helps. I used similar code to handle files coming via this jQuery file upload plugin.
Upvotes: 0