简体   繁体   English

使用C#和MVC3的HttpFileCollectionBase问题上传多个文件

[英]Upload multiple files using HttpFileCollectionBase issue with C# and MVC3

I created a controller which save files. 我创建了一个保存文件的控制器。

The below code is a part of that Controller: 以下代码是该控制器的一部分:

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" );
               }
            }
         }
 }

in ASPX page is simple: 在ASPX页面很简单:

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

The problem is foreach because it returns an error like (I know because I run in Debug mode and placed breakpoint at foreach statement): 问题是foreach因为它返回一个错误(我知道因为我在调试模式下运行并在foreach语句中放置了断点):

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

What is my mistake ? 我的错是什么?

Try like this: 试试这样:

[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");
}

and modify the markup so that the file inputs are named files: 并修改标记,以便文件输入是命名文件:

<input type="file" name="files" />
<input type="file" name="files" />
...// many inputs type file
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 requires an index, so use for instead of foreach . HttpRequestBase.Files需要一个索引,因此使用for而不是foreach

Have a look at this post by Phil Haack which demonstrates how to process multiple file uploads using MVC. 看看Phil Haack的这篇文章 ,演示如何使用MVC处理多个文件上传。 The object you are trying to use is for ASP.NET Webforms. 您尝试使用的对象是ASP.NET Webforms。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM