MVC4中的上传文件总是出现null异常

本文关键字:null 异常 文件 MVC4 | 更新日期: 2023-09-27 17:57:59

我已经在视图中使用上传

<div class="SearchArea">
@using (Html.BeginForm("FileUpload", "Noun", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
     @Html.ValidationSummary();
     <ol>
     <li class="lifile">
     <input type="file" id="fileToUpload" name="file" />
     <span class="field-validation-error" id="spanfile"></span>
     </li>
     </ol>
     <input type="submit" id="btnSubmit" value="Upload" />
}   
</div>

文件上传方法看起来像

 [HttpPost]
public ActionResult FileUpload(HttpPostedFileBase input)
{
    if (input.ContentLength > 0)
    {
        var fileName = Path.GetFileName(input.FileName);
        var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
        input.SaveAs(path);
    }

我总是得到输入为空,我的routeconfig看起来像(我用同一个项目编译wcf):

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    // For general and WCF Configuration 
    routes.MapRoute(
      "Default",
      "{controller}/{action}/{id}",
      new { controller = "Home", action = "Index", id = UrlParameter.Optional },
      new { controller = "^(?!ClassesWebService).*" });
    routes.Add(new ServiceRoute("ClassesWebService", new WebServiceHostFactory(), typeof(WebService.IClassesWebService)));

任何关于如何解决的想法

MVC4中的上传文件总是出现null异常

您的名称不匹配。这是你的名字file:

<input type="file" id="fileToUpload" name="file" />

这里的名称是input:

public ActionResult FileUpload(HttpPostedFileBase input)

将其中一个重命名为另一个。