空时如何处理输入类型文件

时间:2015-04-14 02:26:28

标签: asp.net asp.net-mvc-5

对mvc来说是新手,我正在尝试使用<input type="file" name="file" id="file" />上传文件。当我通过浏览按钮将文件附加到它时,它正在工作。但是如果我在文件为空时尝试保存其他表单值,我会收到一个错误,即Object引用未设置为对象的实例。如果有人能提供帮助,我会很高兴。 这是我的代码的一部分。

控制器

public ActionResult InfoForm([Bind(Include = "Id, Title, Details, Day, Month, Year, Category, Status, ImageName ")] Info info, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    string path = Server.MapPath("~") + "\\Content\\images\\info\\" + file.FileName;
                    file.SaveAs(path);
                    info.ImageName = fileName; // this line saves the name to the database.
                }


                db.Infoes.Add(info);
                db.SaveChanges();
                return RedirectToAction("InfoList");
            }

查看

...
...
@Html.LabelFor(model => model.Category, new { @class = "control-label col-md-2" })
@Html.DropDownListFor(  model => model.Category, new List<SelectListItem>
    {
        new SelectListItem { Text = "UpComing Event", Value = "UpComing Event" },
        new SelectListItem { Text = "What's New",  Value = "What's New"},

    }, new { @class = "form-control" } )

@Html.ValidationMessageFor(model => model.Category)

@Html.LabelFor(model => model.Status, new { @class = "control-label col-md-2" })
@Html.DropDownListFor( model => model.Status, new List<SelectListItem>
                {
                    new SelectListItem { Text = "Enable", Value = "True" },
                    new SelectListItem { Text = "Disable",  Value = "False"},

                }, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Status)

<label class="control-label col-md-2"> Upload Image</label>
<input type="file" name="file" id="file" />
@Html.ValidationMessageFor(model => model.ImageName)
<input type="submit" value="Save" class="btn btn-default" />
...
...

1 个答案:

答案 0 :(得分:1)

如果没有选择文件,则HttpPostedFileBase为null并且您已使用该语句

file.ContentLength

结果为

null.ContentLength  

你可以弄明白其余的

你需要为文件检查null为

if(file!=null)
{ if(file.ContentLength>0)
...
}