I’m having trouble separating files that a user might post to separate input type=”file” fields. I have tried:
var UploadedPicture = Request.Files[0];
if(Path.GetFileName(UploadedPicture.FileName) != String.Empty)
{
var ContentType = UploadedPicture.ContentType;
var ContentLength = UploadedPicture.ContentLength;
var InputStream = UploadedPicture.InputStream;
Session["gMugshot"] = new byte[ContentLength];
InputStream.Read((byte[])Session["gMugshot"], 0, ContentLength);
}
else
{
Session["gMugshot"] = new byte[0];
}
But that only gets one file. I have tried
foreach (HttpPostedFile postedFile in Request.Files)
{
int contentLength = postedFile.ContentLength;
string contentType = postedFile.ContentType;
string fileName = postedFile.FileName;
postedFile.SaveAs(@"c:\test\file" + index + ".tmp");
}
}
But that doesn’t separate them (Also, I don’t want to save the file, I just want to store it in the database, but that part is no problem). They each need to go into separate database fields. I can get this working with a single image, but don’t know how to work with multiples. If possible I would like to work with the input type="file" fields rather than the FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded:false, includeFormTag:false) helper.
Is it possible to retrieve them by the ID of the input element?
When you add multiple input type=file elements to a page, the uploaded files are available in the Request.Files collection. You can iterate that as your code shows and perform whatever action you like on each file in the collection:
If you have different input type=file for specific purposes, you can identify them by providing a name attribute:
The values in the name attribute are available in the Request.Files.AllKeys, which is an array of strings, so you can reference each item by its index e.g.