Request.Files 上的 foreach [英] foreach on Request.Files
问题描述
我正在尝试在 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);
}
之前的代码产生了这个错误:
The previous code generates this error:
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.
我不明白的是为什么 Request.Files[1] 返回一个 HttpPostedFileBase 但当它被迭代时,它返回字符串(大概是文件名).
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
对象.获得密钥后,使用带有密钥(文件名)的 Item
([]
) 属性来获取 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];
...
}
这篇关于Request.Files 上的 foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!