我试图在ASP.NET MVC中上传多个文件,我有这个简单的foreach循环在我的控制器
I'm attempting upload multiple files in ASP.NET MVC and I have this simple foreach loop in my controller
foreach (HttpPostedFileBase f in Request.Files) { if (f.ContentLength > 0) FileUpload(f); }在previous code生成此错误:
The previous code generates this error:
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.我不明白的是为什么Request.Files [1]返回HttpPostedFileBase但是当它的迭代,它返回字符串(presumably文件名)。
What I don't understand is why Request.Files[1] returns an HttpPostedFileBase but when it's iterated over, it returns strings (presumably the file names).
注:我知道这可以用一个for循环来解决。此外,我尝试使用HttpPostedFile,具有相同的错误。
Note: I know this can be solved with a for loop. Also, I tried using HttpPostedFile, with the same error.
推荐答案在 HttpFileCollection 返回文件的键(名字)的枚举,而不是 HttpPostedFileBase 的对象。一旦你拿到钥匙,使用项目( [] )用钥匙(文件名)属性来获取 HttpPostedFileBase 对象。
The enumerator on the HttpFileCollection returns the keys (names) of the files, not the HttpPostedFileBase objects. Once you get the key, use the Item ([]) property with the key (filename) to get the HttpPostedFileBase object.
foreach (string fileName in Request.Files) { HttpPostedFileBase file = Request.Files[fileName]; ... }更多推荐
foreach所Request.Files
发布评论