上传使用HttpFileCollectionBase问题,C#和MVC3多个文件 [英] Upload multiple files using HttpFileCollectionBase issue with C# and MVC3

查看:1570
本文介绍了上传使用HttpFileCollectionBase问题,C#和MVC3多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a controller which save files.

下面code是控制器的一部分:

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

在ASPX页面很简单:

in ASPX page is simple:

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

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

The problem is foreach because it returns me an error like (I know because I run in Debug mode and placed breakpoint at foreach statement):

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

和修改标记,以便该文件输入端被命名文件:

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

这篇关于上传使用HttpFileCollectionBase问题,C#和MVC3多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆