上传的HttpPostedFile为null

19 c# asp.net asp.net-mvc

在视图上:

<% =Html.BeginForm("About", "Home", FormMethod.Post, new {enctype="multipart/form-data "})%>
  <input type="file" name="postedFile" />
  <input type="submit" name="upload" value="Upload" />
<% Html.EndForm(); %>
Run Code Online (Sandbox Code Playgroud)

在Controller中,有这样的东西:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult About(HttpPostedFile postedFile)
{
    //but postedFile is null 
    View();
}
Run Code Online (Sandbox Code Playgroud)

postedFile在About()中为null.我如何上传文件?

Car*_*erg 30

使用HttpPostedFileBase(不是HttpPostedFile)并将参数命名为与表单完全相同.例如.如果你有

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

你必须有方法头:

public ActionResult About(HttpPostedFileBase file1)
Run Code Online (Sandbox Code Playgroud)

  • 我有完全相同的问题,一旦将我的动作参数类型从`HttpPostedFile`更改为`HttpPostedFileBase`,它就可以了.所以应该强调这个建议. (2认同)

Ben*_*ins 7

这不能解释您的参数为空的原因,但您可以直接深入了解请求.尽管如此,这可能不是最"MVC"的方式.在你的方法体中试试这个:

var upload = Request.Files["postedFile"]
if (upload.ContentLength > 0)
{
  // Do whatever
}
Run Code Online (Sandbox Code Playgroud)

要更加"MVC",您可以将代码从控制器中提取到IModelBinder实现中,并使用自定义对象作为方法的参数.这篇Scott Hanselman博客文章展示了实现自定义ModelBinder的步骤.


ern*_*tit 6

用这个

public ActionResult Upload(HttpPostedFileBase excelfile)
Run Code Online (Sandbox Code Playgroud)

改变HttpPostedFileHttpPostedFileBase