文件上传在 MVC4 - 移动模板 ASP.NET 不起作用



我正在使用C#和ASP。NET MVC4用于web应用程序(移动模板)。

现在我的视图中有以下代码:

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

这个在我的控制器里:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string path = System.IO.Path.Combine(Server.MapPath("~/Content"), System.IO.Path.GetFileName(file.FileName));
        file.SaveAs(path);
        ViewBag.Message = "File uploaded successfully";
        return View();
    }

当我运行应用程序并尝试上传文件时,我得到Visual Studio中的"对象引用未设置为对象的实例。"消息。但我知道上面的代码在ASP中运行得很好。NET MVC3。

有人能帮我吗?

将此属性添加到表单:data-ajax="false"

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

您不必使用HttpPostedFileBase,因为事实上您不必在[HttpPost]操作中接收任何参数。只要你的表单设置为enctype = "multipart/form-data"(你已经这样做了),你就可以从这样的请求中获得你的文件:

var file = Request.Files[0];

最新更新