【问题标题】:Upload multiple files using HttpFileCollectionBase issue with C# and MVC3使用 C# 和 MVC3 的 HttpFileCollectionBase 问题上传多个文件
【发布时间】:2012-02-29 14:04:33
【问题描述】:

我创建了一个保存文件的控制器。

以下代码是该控制器的一部分:

if ( Request.Files.Count != 0 ) {
      HttpFileCollectionBase files = Request.Files;

      foreach ( HttpPostedFileBase file in files ) {
            if ( file.ContentLength > 0 ) {
               if ( !file.ContentType.Equals( "image/vnd.dwg" ) ) {
                  return RedirectToAction( "List" );
               }
            }
         }
 }

在 ASPX 页面中很简单:

<input type="file" name="file" />
<input type="file" name="file" />
...// many inputs type file

问题是foreach,因为它返回类似的错误(我知道是因为我在调试模式下运行并在 foreach 语句中放置了断点):

Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFileBase'.

我的错误是什么?

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3


    【解决方案1】:

    试试这样:

    [HttpPost]
    public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
    {
        if (files != null && files.Count() > 0)
        {
            foreach (var uploadedFile in files)
            {
                if (uploadedFile.ContentType != "image/vnd.dwg") 
                {
                    return RedirectToAction("List");
                }
    
                var appData = Server.MapPath("~/app_data");
                var filename = Path.Combine(appData, Path.GetFileName(uploadedFile.FileName));
                uploadedFile.SaveAs(filename);                    
            }
        }
    
        return RedirectToAction("Success");
    }
    

    并修改标记,使文件输入命名为文件:

    <input type="file" name="files" />
    <input type="file" name="files" />
    ...// many inputs type file
    

    【讨论】:

    • 我尝试了上面的代码(似乎是我的代码),但我改变了对foreach 的看法。我现在使用for 语句。而且效果很好。
    • 最后提到:我的控制器函数中没有参数
    • 我尝试了这个解决方案,但我没有检索到任何值!
    【解决方案2】:
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        // this file's Type is HttpPostedFileBase which is in memory
    }
    

    HttpRequestBase.Files 需要索引,因此请使用for 而不是foreach

    【讨论】:

      【解决方案3】:

      查看 Phil Haack 的 this post,它演示了如何使用 MVC 处理多个文件上传。您尝试使用的对象是 ASP.NET Webforms。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多