C# 在 Request.Files 上 foreach

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1760510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:34:58  来源:igfitidea点击:

foreach on Request.Files

c#asp.netfile-upload

提问by Omar

I'm attempting upload multiple files in ASP.NET MVC and I have this simple foreach loop in my controller

我正在尝试在 ASP.NET MVC 中上传多个文件,并且我的控制器中有这个简单的 foreach 循环

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'. 

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).

我不明白的是为什么 Request.Files[1] 返回一个 HttpPostedFileBase 但是当它被迭代时,它返回字符串(大概是文件名)。

Note: I know this can be solved with a for loop. Also, I tried using HttpPostedFile, with the same error.

注意:我知道这可以用 for 循环解决。另外,我尝试使用 HttpPostedFile,但出现相同的错误。

采纳答案by tvanfosson

The enumerator on the HttpFileCollectionreturns the keys (names) of the files, not the HttpPostedFileBaseobjects. Once you get the key, use the Item([]) property with the key (filename) to get the HttpPostedFileBaseobject.

上的枚举器HttpFileCollection返回文件的键(名称),而不是HttpPostedFileBase对象。获得密钥后,使用Item( []) 属性和密钥(文件名)来获取HttpPostedFileBase对象。

foreach (string fileName in Request.Files)
{
    HttpPostedFileBase file = Request.Files[fileName];

    ...
}

回答by Joe Barone

You might try iterating the strings and casting them to HttpPostedFile instead, like this:

您可以尝试迭代字符串并将它们转换为 HttpPostedFile,如下所示:

foreach (string file in Request.Files)
    {
        HttpPostedFile hFile = Request.Files[file] as HttpPostedFile;
        if (hFile.ContentLength > 0)
            FileUpload(hFile);
    }

回答by Harvey

Unfortunately tvanfosson's answer did not work for me. Although the files would upload just fine, and no error would be thrown, a problem would occur where only one of the files would be used, so the same file would be saved twice rather than using them both.

不幸的是,tvanfosson 的回答对我不起作用。虽然文件上传得很好,不会抛出错误,但会出现一个问题,只使用一个文件,所以同一个文件会保存两次,而不是同时使用它们。

It seemed to be a problem with the foreach statement looping through the names of each file in the Request.Files, for some reason it wasn't working as a key for me, and only the first file would be selected every time.

循环遍历 Request.Files 中每个文件的名称的 foreach 语句似乎有问题,出于某种原因,它对我来说不是一个键,每次只会选择第一个文件。

HttpFileCollectionBase files = Request.Files;

for(var i = 0; i < files.Count; i++)
{
    HttpPostedFileBase file = files[i];

    ...
}

回答by nguyenhoai890

With my tab HTML is:

我的标签 HTML 是:

<input class="valid" id="file" name="file" multiple="" type="file">

Request.Files will have duplicate name in array. So you should solve like this:

Request.Files 将在数组中具有重复名称。所以你应该这样解决:

for (int i = 0; i < Request.Files.Count; i++ ){
    HttpPostedFileBase fileUpload = Request.Files[i];

回答by Ivan DCosta

The following code worked for me.

以下代码对我有用。

  HttpResponseMessage result = null;
  var httpRequest = System.Web.HttpContext.Current.Request;
  HttpFileCollection uploadFiles = httpRequest.Files;
  var docfiles = new List<string>();

  if (httpRequest.Files.Count > 0){
      int i;
      for (i = 0; i < uploadFiles.Count; i++) {
          HttpPostedFile postedFile = uploadFiles[i];
          var filePath = @"C:/inetpub/wwwroot/test1/reports/" + postedFile.FileName;
          postedFile.SaveAs(filePath);
          docfiles.Add(filePath);
      }
      result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
  } else {
      result = Request.CreateResponse(HttpStatusCode.BadRequest);
  }

  return result;
}

回答by Akira Yamamoto

We can use LINQ to do this and still use foreach as asked:

我们可以使用 LINQ 来做到这一点,并且仍然按照要求使用 foreach:

var files = Enumerable.Range(0, Request.Files.Count)
    .Select(i => Request.Files[i]);

foreach (var file in files)
{
    // file.FileName
}

As @tvanfosson said, the enumerator returns the file names as strings, not the HttpPostedFileBase. This method HttpPostedFileBase this[string name]returns the object we want. If HttpFileCollectionBaseimplemented IEnumerable<HttpPostedFileBase>then we could do the foreach normally. However, it implements a non-generic IEnumerable.

正如@tvanfosson 所说,枚举器将文件名作为字符串返回,而不是HttpPostedFileBase. 这个方法HttpPostedFileBase this[string name]返回我们想要的对象。如果HttpFileCollectionBase实现,IEnumerable<HttpPostedFileBase>那么我们可以正常执行 foreach。但是,它实现了一个非通用的IEnumerable.

回答by Jnr

You can get the HttpPostedFileout of the HttpFileCollectionusing foreachlike this:

您可以像这样HttpPostedFile停止HttpFileCollection使用foreach

foreach (var obj in fileCollection)
{
    HttpPostedFile file = fileCollection.Get(obj.ToString());
}