InvalidCastexception上传多个图像

时间:2016-11-19 16:49:04

标签: asp.net asp.net-mvc asp.net-mvc-4

大家好我正在创建一个使用MVC 5的应用程序,带有代码第一个数据库,下面的代码显示了我目前尝试用来上传多个图像的代码但是在尝试转换'System.String'时我得到了一个InvalidCastexception输入'System.Web.HttpPostedFileBase'。

感谢您的时间,非常感谢您对此问题的任何帮助。

图像控制器

   // GET: Images/Upload
            [HttpGet]
            public ActionResult Upload()
            {
                return View();
            }

            // POST: Images/Upload
            [HttpPost]
            public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
            {

                    HttpFileCollectionBase files = Request.Files;
                    foreach (HttpPostedFileBase file in files)
                    {
                        int length = file.ContentLength;
                        string type = file.ContentType;
                        string filename = file.FileName;
                    }
                    return RedirectToAction("Upload");

            }

上传视图

@{Layout = null;}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Upload</title>
</head>
<body>
    <form method="post" action="~/Images/Upload" id="form1" enctype="multipart/form-data">
                    @if (ViewData.Model != null)
                    {
                        foreach (var item in ViewData.Model)
                        {
                            <img src="/Images/@item["Path"]" alt="FileUpload   Image" />
                        }
                    }

                    <input type="file" name="uploadFiles" id="FileUpload" multiple="multiple" />

                   <input type="submit" name="btnSubmit" value="Upload" id="btnSubmit" />      
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

你不能那样做

foreach (HttpPostedFileBase file in files)

因为HttpFileCollection的枚举器会返回文件的名称(string)但不会返回HttpPostedFileBase,因此您将获得InvalidCastexception

在循环中使用uploadFiles而不是HttpFileCollectionBase

public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
{
        foreach (var file in uploadFiles)
        {
            int length = file.ContentLength;
            string type = file.ContentType;
            string filename = file.FileName;
        }
        return RedirectToAction("Upload");
}

或使用for和索引:

HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
     int length = files[i].ContentLength;
    string type = files[i].ContentType;
    string filename = files[i].FileName;
}