【问题标题】:Uploading and processing multiple files using MVC使用 MVC 上传和处理多个文件
【发布时间】:2015-09-20 05:46:53
【问题描述】:

我正在尝试在我的 Web 应用程序上上传多个文件。因此我使用IEnumerable<HttpPostedFileBase> 类在每个文件中循环。但我收到一条错误消息 -

错误System.Collections.Generic.IEnumerable<System.Web.HttpPostedFileBase> 不包含“ContentLength”的定义,并且找不到接受System.Collections.Generic.IEnumerable<System.Web.HttpPostedFileBase 类型的第一个参数的扩展方法“ContentLength”(您是否缺少 using 指令或程序集引用?)

此错误适用于 HttpPostedFileBase 类中存在的所有属性。我正在尝试编辑该课程,但它不允许。我尝试在我的 ViewModel 中创建一个 IEnumerable 的 HttpPostedFileBase 类,但它再次失败。我在这里想念什么?

更新 - 代码: 查看

<div class="col-sm-8">                                  
 <input type="file" name="Files" id="file1" class="form-control" />
  <input type="file" name="Files" id="file2" class="form-control" />
  <input type="submit" value="Save" class="btn btn-default" name="Command"/>   
</div>

控制器

public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> Files)
{
     foreach (var item in Files)
     { 
           if (Files != null && Files.ContentLength > 0)
           {
                FileUpload up = new FileUpload();
                up.PersonId = model.PersonId;
                up.FileName = System.IO.Path.GetFileName(Files.FileName);
                up.MimeType = Files.ContentType;
                up.FileContent = Files.Content;
                bll.AddFileUpload(up);
            }
     }
     return View();
}

【问题讨论】:

  • 请分享一些您用于处理 HttpPostedFileBase 项目的代码,因为您似乎试图以错误的方式访问集合
  • 请看我编辑的问题,我已经包含了代码。谢谢

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


【解决方案1】:

问题出在这里:

foreach (var item in Files)
    if (Files != null && Files.ContentLength > 0)

您正在使用 foreach 迭代集合,但您仍然检查名为 FileIEnumerable 而不是每个项目。你想要的是:

foreach (var item in Files)
    if (item != null && item.ContentLength > 0)

附带说明,您可以使用Enumerable.Where 过滤掉项目:

foreach (var item in Files.Where(file => file != null && file.ContentLength > 0))
{
    FileUpload up = new FileUpload
    {
         PersonId = model.PersonId,
         FileName = System.IO.Path.GetFileName(item.FileName),
         MimeType = item.ContentType,
         FileContent = item.Content,
     };
     bll.AddFileUpload(up);
}

【讨论】:

    【解决方案2】:

    您尝试在集合上调用.ContentLength,而不是在该集合中的文件上调用。相反,请尝试以下方法:

    // given postedFiles implements IEnumerable<System.Web.HttpPostedFileBase
    foreach(var postedFile in postedFiles) {
     var len = postedFile.ContentLength
    }
    

    【讨论】:

      【解决方案3】:

      您的代码试图访问集合本身,但您需要像这样访问集合项:

      foreach (var item in Files)
      {
      
      FileUpload up = new FileUpload();
      up.PersonId = model.PersonId;
      up.FileName = System.IO.Path.GetFileName(item.FileName);
      up.MimeType = Files.ContentType;
      up.FileContent = item.Content;
      bll.AddFileUpload(up);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-02
        • 1970-01-01
        • 2015-11-03
        • 2013-11-01
        • 1970-01-01
        • 2018-09-04
        • 2011-01-15
        • 1970-01-01
        相关资源
        最近更新 更多