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

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

我创建了一个保存文件的 Controller 。

以下代码是该 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" );
               }
            }
         }
 }

在 ASPX 页面中很简单:

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

问题出在 foreach 上,因为它会返回如下错误(我知道是因为我在 Debug模式下运行并在 foreach 语句处放置了断点):

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

我的错误是什么?

最佳答案

像这样尝试:

[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

关于c# - 使用 C# 和 MVC3 的 HttpFileCollectionBase 问题上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500550/

相关文章:

c# - 使用 Moq 模拟 HttpApplicationState 时似乎无法设置对象

c# - MVC 3 将模型项传递给@Html.ActionLink 文本?

asp.net - 我可以创建一个不回发的 ASP.NET ImageButton 吗?

jquery - ASP.NET MVC + jQuery - 当我通过 jQuery $.post 表单时,如何保留 .NET 行结尾?

asp.net - IValidatableObject 验证方法在 DataAnnotations 失败时触发

jquery - ASP.net MVC 3 Razor - jQuery 智能感知

c# - Windows 窗体应用程序中的 UI 控件重叠和字体问题

java - Android viewPager使用本地html内存不足

javascript - 将注释中的数据传递到 aspx 页面

c# - 如何获取 List<t> 项的字符串值