【问题标题】:Error in ASP.NET MVC file upload [duplicate]ASP.NET MVC 文件上传错误 [重复]
【发布时间】:2017-09-25 10:28:24
【问题描述】:

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

<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)

【问题讨论】:

  • 标签 enctype="multipart/form-data" 不应该在表单标签中吗?
  • 是的!最后,谢谢伙计)

标签: asp.net-mvc


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这个

    在表单中添加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; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2016-07-02
      • 2016-05-04
      • 2011-07-08
      • 2013-06-10
      相关资源
      最近更新 更多