【问题标题】:Why is MVC HttpPostedFileBase always null?为什么 MVC HttpPostedFileBase 总是为空?
【发布时间】:2016-12-07 10:13:03
【问题描述】:

这是我的观点

测试上传文件

<form action="@Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <label for="file">Filename:</label>
    <input type="file" name="files" id="files" />

    <input type="submit" name="submit" value="Upload" />
</form>

这是我的控制器

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
          { 
              if (files != null)
                {
                 foreach (var file in files)
                   {
                    try
                     {
                      if (file != null && file.ContentLength > 0)
                        {
                          var fileName = file.FileName;
                          var path = Path.Combine(Server.MapPath(@"\Upload"), fileName);
                          file.SaveAs(path);

                          ViewBag.Message = "File uploaded successfully";
                         }
                       }
                      catch (Exception ex)
                      {
                        ViewBag.Message = "ERROR:" + ex.Message.ToString();
                       }
                   }
                 }
               return View();
             }

问题是 HttpPostedFileBase 文件始终为空。我找不到问题。

【问题讨论】:

标签: c# asp.net-mvc file-upload


【解决方案1】:

您也可以像这样使用Request.Files 处理文件:

public ActionResult Index()
{ 
   if (Request.Files.Count > 0)
   {
      var file = Request.Files[0];    
      if (file != null && file.ContentLength > 0)
      {
         var fileName = Path.GetFileName(file.FileName);
         var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
         file.SaveAs(path);
      }
   }
}

对于第二个问题,请尝试在Html.BeginForm 之间使用它,而不是像这样使用form:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <label>Filename:</label>
    <input type="file" name="file1"/>
    <input type="submit" name="submit" value="Upload" />
}

【讨论】:

  • 我不知道为什么,但它仍然无法正常工作。 Request.Files.Count 始终为 0。我必须使用普通的 html 表单而不是使用 html 助手。
  • 是否有可能来自输入的 id 和属性标签?不输入“id”和label不输入“for”可以试试吗?
  • @using (Html.BeginForm("Index", "Fax", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() &lt;label&gt;Filename:&lt;/label&gt; &lt;input type="file" name="files" /&gt; &lt;input type="submit" name="submit" value="Upload" /&gt; } 我把它改成这个。但它仍然无法正常工作。
【解决方案2】:

这里是一个如何使用表单提交方法的例子

您的 HTML 部分

<form id="formTest" method="post" enctype="multipart/form-data">

        <label for="file">Filename:</label>
        <input type="file" name="files" id="files" />

        <input type="submit" name="submit" value="Upload" />
    </form>


脚本

<script type="text/javascript">
var form = document.getElementById('formTest').onsubmit = function (e) {
        e.preventDefault();
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('files');
    if (fileInput != "" && fileInput.files.length > 0) {
        //Iterating through each files selected in fileInput
        for (i = 0; i < fileInput.files.length; i++) {
            //Appending each file to FormData object
            formdata.append(fileInput.files[i].name, fileInput.files[i]);
        }
        //Creating an XMLHttpRequest and sending
        var xhr = new XMLHttpRequest();

           var url = '@Url.Action("Index","Home")';
        xhr.open('POST', url);
        xhr.send(formdata);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;

            }
        }
        return false;
    }
}
</script>


C#

public ActionResult Index()
{ 
   if (Request.Files.Count > 0)
   {
      var file = Request.Files[0];    
      if (file != null && file.ContentLength > 0)
      {
         var fileName = Path.GetFileName(file.FileName);
         var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
         file.SaveAs(path);
      }
    return View();

   }
}

【讨论】:

  • 我曾尝试使用您的上述解决方案,效果很好。太感谢了。但是为什么我的正常上传文件(不涉及javascript)不起作用?可以不使用javascript吗? @user55
  • 我的荣幸。正如我提到的,您的代码在我的机器上运行良好,无需使用任何 JavaScript。
  • 如果它解决了你的问题,那么请将其标记为答案,这样其他人就不会再发布这个问题的答案了..
猜你喜欢
  • 2013-10-16
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 2019-09-17
相关资源
最近更新 更多