我正在努力将我上传的图像添加到我的数据库表中,在具有MVC 5和EF 6的代码第一个项目中。每个输入,即Filename,FirstName,Phone no。正在更新数据库,但我无法存储图像数据存储在我的数据库表上。 (再次清除混乱,我不是试图存储图像本身。)
我尝试过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);
你可以试试:
@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" })