0

我正在尝试通过 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)
4

3 回答 3

2

您应该将 enctype 属性添加到表单中。

@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post,
                       new { enctype = "multipart/form-data" }))
于 2013-05-18T16:34:14.930 回答
0

作为参数添加new { enctype = "multipart/form-data" }到您的表单中,您就可以开始了。它看起来像:

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

并且不要检查文件大小以进行存在控制。我建议在控制器端控制它是否为空。

于 2013-05-18T16:34:43.510 回答
0

代替

@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post))

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

要了解有关 enctype="multipart/form-data" 含义的更多信息,请参见此处

于 2013-05-18T16:35:18.440 回答