foreach所Request.Files [英] foreach on Request.Files

查看:198
本文介绍了foreach所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);
}

在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆