我尝试在foreach MVC中上传多个文件,我的控制器中有一个简单的ASP.NET循环。
foreach (HttpPostedFileBase f in Request.Files)
{
if (f.ContentLength > 0)
FileUpload(f);
}
前面的代码生成了这个错误:
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.
我不明白的是为什么Request.Files1返回一个HttpPostedFileBase,但是当它被迭代时,它返回字符串(大概是文件名)。
注意:我知道这可以通过一个for循环来解决。此外,我还尝试使用HttpPostedFile,但出现了相同的错误。
发布于 2009-11-19 10:30:34
HttpFileCollection
上的枚举器返回文件的键(名称),而不是HttpPostedFileBase
对象。获取密钥后,使用带有密钥(文件名)的Item
([]
)属性来获取HttpPostedFileBase
对象。
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
...
}
发布于 2014-12-08 12:23:34
在我的选项卡上,HTML是:
<input class="valid" id="file" name="file" multiple="" type="file">
Request.Files将在数组中具有重复的名称。所以你应该像这样解决:
for (int i = 0; i < Request.Files.Count; i++ ){
HttpPostedFileBase fileUpload = Request.Files[i];
发布于 2015-10-01 07:01:57
我们可以使用LINQ来做到这一点,并且仍然可以按照要求使用foreach:
var files = Enumerable.Range(0, Request.Files.Count)
.Select(i => Request.Files[i]);
foreach (var file in files)
{
// file.FileName
}
正如@tvanfosson所说,枚举器返回字符串形式的文件名,而不是HttpPostedFileBase
。这个方法HttpPostedFileBase this[string name]
返回我们想要的对象。如果HttpFileCollectionBase
实现了IEnumerable<HttpPostedFileBase>
,那么我们就可以正常地执行foreach。但是,它实现了一个非泛型IEnumerable
。
https://stackoverflow.com/questions/1760510
复制相似问题