MVC上载文件对象引用未设置为对象的实例

时间:2018-01-08 09:08:17

标签: asp.net-mvc

感谢您的时间。在开始之前,我想向您展示我的代码。

模型

public class Files
{
    public HttpPostedFileBase Picture { get; set; } 
}

查看

@model FileUpload.Models.Picture
....
@using (Html.BeginForm("UploadFileTest", "FileUpload", FormMethod.Post, new { enctype =  "multipart/form-data" }))
{
    <input type="file" name="Picture" id="Picture" />
    <input type="submit" name="submit" value="Upload" />
}

FileUploadController

[HttpPost]
public ActionResult UploadFileTest(Picture file)
{
    if (file.File.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.File.FileName);
        var path = Path.Combine(Server.MapPath("~/Files/"), fileName);
        file.File.SaveAs(path);
    }
    return RedirectToAction("UploadFileTest");
}

上传文件并单击“提交”后,收到此错误消息

  

对象引用未设置为对象的实例。

if (file.FileFile.ContentLength > 0)

1 个答案:

答案 0 :(得分:0)

像这样更改FileUploadController

[HttpPost]
public ActionResult UploadFileTest(HttpPostedFileBase file)
{
    if (file.File.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.File.FileName);
        var path = Path.Combine(Server.MapPath("~/Files/"), fileName);
        file.File.SaveAs(path);
    }
    return RedirectToAction("UploadFileTest");
}