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



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

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

这是我的模型,电影.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);

你可以试试:

@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" })

最新更新