Upload multiple files / access input id at server site
I am trying to upload a couple of files. The upload itself works well for a single upload but I can't figure out how to access the element name to make sure each upload is assigned to the correct field. HttpPostedFileBase doesn't seem to contain that type of info anymore.
public ActionResult Edit(int id, FormCollection collection) {
Report report = re.GetReport(id);
var fileNames = new List<string>();
foreach (string file in Request.Files) {
var postedFile = Request.Files[file] as HttpPostedFileBase;
if (postedFile.ContentLength == 0)
continue;
fileNames.A开发者_JS百科dd(UploadFile(basedir, postedFile));
}
// Rather than guessing which is which I'd like to get the field name or id.
report.Image = fileNames[0];
report.File = fileNames[1];
UpdateModel(report, "report");
rep.Save();
In the view I have
<%: Html.LabelFor(model => model.report.Image)%>
<input id="report_Image" type="file" name="Image" />
<%: Html.LabelFor(model => model.report.File)%>
<input id="report_Image" type="file" name="File" />
Thanks, Duffy
var fileNames = new List<string>();
foreach (string file in Request.Files) {
var postedFile = Request.Files[file] as HttpPostedFileBase;
if (postedFile.ContentLength == 0)
continue;
fileNames.Add(UploadFile(basedir,postedFile));
}
The variable file in the foreach contain the name of your input field. So its value will be Image and File Respectively. I checked it in MVC2
So you can do like this
var fileNames = new Dictionary<string,string>();
foreach (string file in Request.Files)
{
var postedFile = Request.Files[file] as HttpPostedFileBase;
if (postedFile.ContentLength == 0)
continue;
fileNames.Add(file,UploadFile(basedir,postedFile));
}
//Now you have added the values with key so you can use the
//input field name to access them
report.Image = fileNames["Image"];
report.File = fileNames["File"];
Phil Haack blogged about this recently, maybe his example will help.
You could also look at the extension of the file to determine which file it is.
Can you use Request.Files["File"] and Request.Files["Image"]?
I use uploadify in my MVC apps. It's free and a great solution for uploading multiple files.
http://www.uploadify.com/
http://trycatchfail.com/blog/post/2009/05/13/ASPNET-MVC-HtmlHelper-for-Uploadify-Take-One.aspx
精彩评论