使用类型文件的输入时,Request.Files.Count始终为0

时间:2018-04-04 10:50:17

标签: asp.net-mvc

我无法获取上传的文件,它始终将Request.Files.Count显示为0.

@using (Html.BeginForm("HandleForm", "Home", new { EncType = "multipart/form-data" }))
{    
    <div>Upload Something: 
        <input type="file" name="uploadedFile" />
    </div>
    <br/>
        <input type="submit" value="Submit" />
} 

控制器操作:

 public ActionResult HandleForm(HttpPostedFileBase uploadedFile)
        {                
            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("FormResults");
        }

1 个答案:

答案 0 :(得分:2)

您使用错误overloadBeginForm()并为enctype添加路由值,而不是html属性。

您需要使用this overload

@using (Html.BeginForm("HandleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))`