简体   繁体   English

为什么MVC HttpPostedFileBase总是为空?

[英]Why is MVC HttpPostedFileBase always null?

This is my View 这是我的观点

Test Upload File 测试上传文件

<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>

This is my Controller 这是我的控制器

 [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();
             }

The problem is the HttpPostedFileBase files is always null. 问题是HttpPostedFileBase文件始终为null。 I cant find the problem. 我找不到问题。

在此输入图像描述

Here is an example how to use form onsubmit method 以下是如何使用表单onsubmit方法的示例

Your HTML part 你的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 脚本

<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# 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();

   }
}

You can also handle files with Request.Files like this: 您还可以使用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);
      }
   }
}

And for your second question, please try to use it between Html.BeginForm instead of form like this: 对于你的第二个问题,请尝试在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" />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM