首页 > 解决方案 > 如何在 Asp.Net MVC 5 上使用实体框架 6 将图像(图像路径/二进制)添加到数据库?

问题描述

我正在努力将我上传的图像添加到我的数据库表中,在 MVC 5 和 EF 6 的代码优先项目中。每个输入,即文件名、名字、电话号码。正在更新数据库,但我无法将图像数据存储在我的数据库表中。(再次清除混乱,我不是要存储图像本身。)

我试过 VarChar(Max) 和 VarBinary(Max)。我在视图、控制器和模型中发布了该特定类的一些代码。

这是我的模型,Movie.cs

        public byte[] Poster { get; set; }
        public string AltText { get; set; }

我的控制器:

     [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Create([Bind(Include = 
      "MovieID,MoviesName,ReYear,Description, 
       UnitPrice,Rating,AltText,GenreID")] Movie movie, HttpPostedFileBase 
            img)
           {

           if (ModelState.IsValid)
              {
               if (movie.img.ContentLength > 0)
                  {
                   string fileName = Path.GetFileName(movie.img.FileName);
                   string extension = 
                      Path.GetExtension(movie.img.FileName);
                     fileName = fileName + DateTime.Now.ToString 
                                ("yymmssfff")+ extension;
                     movie.AltText = "~/Content/Poster/" + fileName;
                     fileName = 
                        Path.Combine(Server.MapPath("~/Content/Poster"), 
                         fileName);
                  movie.img.SaveAs(fileName);
                using (MovieContext db = new MovieContext())
                {

                    db.Movies.Add(movie);
                    db.SaveChanges();
                }

            }
            return RedirectToAction("Index");
        }

        ViewBag.GenreID = new SelectList(db.Genres, "GenreID", 
                          "GenreType", movie.GenreID);
        return View(movie);
    }

我的观点:

        @model BigHits.Models.Movie
        @using (Html.BeginForm("Create", "Movies", null, FormMethod.Post, 
        new { enctype = "multipart/form-data" }))

       <div class="form-group">
       @Html.LabelFor(model => model.AltText, htmlAttributes: new { @class 
                            = "control-label col-md-2" })
         <div class="col-md-10">
         <input type="file" id="img" name="img"  />
         </div>
       </div>

现在,每当我尝试上传图像时,都会出现此错误。

  Object reference not set to an instance of an object. 
   Description: An unhandled exception occurred during the execution of the 
   current web request. Please review the stack trace for more information 
   about the error and where it originated in the code. 

   Exception Details: System.NullReferenceException: Object reference not 
   set to an instance of an object.

  Source Error: 


  Line 92:    string fileName = Path.GetFileName(movie.img.FileName);
  Line 93:    string extension = Path.GetExtension(movie.img.FileName);

标签: asp.netasp.net-mvc-5entity-framework-6ef-code-first

解决方案


你可以试试:

@Html.LabelFor(model => model.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model=>model.'Your attributes', new { @class = "form-control", @type="file" })

推荐阅读