ASP.NET MVC文件上载出错

时间:2017-04-27 14:41:33

标签: asp.net-mvc

看,伙计们。我正在尝试上传一些信息,但无法加载文件。只需检查代码: 视图:

<form method="post" data-toggle="validator" role="form">
        <div class="not-that-right">
            <div class="form-group">
                <label for="Photo">Photo</label>
                <input type="file"
                       id="Photo"
                       name="Photo"
                       accept="image/gif, image/jpeg, image/png"
                       onchange="show(this)" />
            </div>

            <img id="onLoad"
                 src="#"
                 alt="photo is optional">
        </div>...........some another info.
</form>

控制器:

[HttpPost]
public ActionResult Create(InventorViewModel inventor)
{
    inventor.Photo = Request.Files["Photo"];
    InventorEntity onAdding = new InventorEntity()
    {
        FirstName = inventor.FirstName,
        SurName = inventor.SurName,
        DateOfBirth = inventor.DateOfBirth,
        Sex = inventor.Sex,
        HigherEducation = inventor.HigherEducation == "on" ? true : false,
        Description = inventor.Description,
        Country = uow.UserBL.GetCounryById(int.Parse(inventor.Country)),
        Photo = ImageConvertor.ConvertToBytes(inventor.Photo)
    };
    uow.UserBL.CreateInventor(onAdding);
    return RedirectToAction("Index");
}

所以当我将此模型添加到数据库时,照片为NULL。有任何想法吗?也许我应该改变一些东西(或所有xD)

2 个答案:

答案 0 :(得分:1)

尝试在表单中插入属性enctype="multipart/form-data"

答案 1 :(得分:0)

试试这个

enctype = "multipart/form-data"添加到表单并将控制器代码更改为此

 if (Request.Files.Count > 0)
 {
     var file = Request.Files[0];

     if (file != null && file.ContentLength > 0)
     {
        var fileName = Path.GetFileName(file.FileName);
        // do what you want to do
     }
 }

您还可以通过添加HttpPostedFileBase将文件作为视图模型的一部分。模型绑定器将文件绑定到该属性。

public HttpPostedFileBase attachment { get; set; }