我正在尝试通过MVC3上传文件 这是我的观点:
@{
ViewBag.Title = "Pic";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}
@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />
}
这是我的行动:
public ActionResult FileUpload()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
我的代码出了什么问题? 我有这个错误
Object reference not set to an instance of an object.
在这一行
if (uploadFile.ContentLength > 0)
答案 0 :(得分:2)
您应该在表单中添加enctype属性。
@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post,
new { enctype = "multipart/form-data" }))
答案 1 :(得分:0)
将new { enctype = "multipart/form-data" }
作为参数添加到表单中,您就可以开始了。它看起来像:
@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post,
new { enctype = "multipart/form-data" }))
不要检查存在控件的文件大小。我建议控制它是否在控制器端为空。
答案 2 :(得分:0)
替换
@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post))
带
@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post, new { enctype="multipart/form-data"}))
要详细了解enctype =“multipart / form-data”的含义,请参阅here