【发布时间】:2019-09-08 06:41:48
【问题描述】:
在使用 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.net asp.net-mvc-5 entity-framework-6 ef-code-first