HttpPostedFileBase始终在ASP.NET MVC中返回null

Jos*_*Son 53 asp.net-mvc file-upload

我在ASP.NET MVC中上传文件时遇到问题.我的代码如下:

视图:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index2</h2>
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <input type="file" />
  <input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)

控制器:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
    if (uploadFile != null && uploadFile.ContentLength > 0)
    {
        string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName));
        uploadFile.SaveAs(filePath);
    }
    return View();
}
Run Code Online (Sandbox Code Playgroud)

但uploadFile总是返回null.任何人都可以找出原因??

dot*_*tep 118

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index2</h2>
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <input type="file" name="uploadFile"/>
  <input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)

你必须提供姓名输入类型的文件,以uploadFile以模特在ASP.net MVC绑定工作,
还要确保您输入的文件类型和参数名的名字HttpPostedFileBase是相同的.

  • 我没有错过字段名称,但由于缺少表单定义中的enctype参数而导致相同的"null"问题.谢谢你的例子. (46认同)
  • 并且controller参数中的名称必须与表单中的名称匹配. (8认同)
  • 多亏了这个 - 我正在进行多个文件上传(所以我的FileUpload方法的参数类型为IEnumerable <HttpPostedFileBase>),并且我将所有文件输入元素命名为相同的参数名称,它就像一个魅力. (2认同)

rob*_*lem 9

我曾尝试过针对此主题在线发布的大部分解决方案,但发现使用解决方法更好.

我做了什么并不重要HttpPostedFileBase和/或HttpPostedFile总是为空.使用HttpContext.Request.Files集合似乎没有任何麻烦.

例如

 if (HttpContext.Request.Files.AllKeys.Any())
        {
            // Get the uploaded image from the Files collection
            var httpPostedFile = HttpContext.Request.Files[0];

            if (httpPostedFile != null)
            {
                // Validate the uploaded image(optional)

                // Get the complete file path
                var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(@"\")));

                // Save the uploaded file to "UploadedFiles" folder
                httpPostedFile.SaveAs(fileSavePath);
            }
        }
Run Code Online (Sandbox Code Playgroud)

在上面的例子中我只抓取第一个文件,但这只是循环通过集合保存所有文件的问题.

HTH


小智 5

在我的场景中问题是id属性,我有这个:

<input type="file" name="file1" id="file1" />
Run Code Online (Sandbox Code Playgroud)

灵魂就是删除id:

<input type="file" name="file1"  />
Run Code Online (Sandbox Code Playgroud)

  • 在我的情况下,我使用的是HttpPostedFile而不是HttpPostedFileBase ..程序员错误:/ (3认同)

jmo*_*eno 5

虽然不是针对该特定用户的答案,但我想指出HTML 要求表单标记具有值为 multipart/form-data 的 enctype 属性。当然,属性及其值都必须正确。

对于mvc来说,这意味着在使用beginform时,应该使用带有htmlAttributes参数的版本