在 ASP.NET MVC 5 中将图像添加到数据库
Adding a image to database in ASP.NET MVC 5
我正在尝试使用 ASP.NET MVC 和 Entity Framework 将图像添加到数据库 table。
我已经对名为 'AspNetUsers' 的现有 ASP.NET MVC table 进行了迁移,并在其中添加了一些新列。
其中一列是ProfilePicture,是byte[]类型。
当我尝试注册新用户时,我希望用户提供其个人资料图片以及其他数据。
这是具有新添加属性的 ApplicationUser class:
public class ApplicationUsers : IdentityUser
{
public string Name { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string DateOfBirth { get; set; }
public byte[] ProfilePicture { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUsers> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
为了将图像放入 table,我使用了名为 ExtendedIdentityModels 的 class 包装器。这个class继承自RegisterViewModelclass,它只有一个属性 UserProfilePicture,类型为HttpPostedFileBase,用于从用户页面获取图像。
public class ExtendedIdentityModels : RegisterViewModel
{
public HttpPostedFileBase UserProfilePicture { get; set; }
}
我更改了控制器中的 Register 方法以将此新属性添加到数据库中:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(ExtendedIdentityModels model)
{
if (ModelState.IsValid)
{
if (model.UserProfilePicture != null)
{
if (model.UserProfilePicture.ContentLength > (4 * 1024 * 1024))
{
ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
return View();
}
if (!(model.UserProfilePicture.ContentType == "image/jpeg" || model.UserProfilePicture.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
}
}
byte[] data = new byte[model.UserProfilePicture.ContentLength];
model.UserProfilePicture.InputStream.Read(data, 0, model.UserProfilePicture.ContentLength);
var user = new ApplicationUsers() { UserName = model.Email, Email = model.Email, Name = model.Name, LastName = model.LastName, City = model.City, DateOfBirth = model.DateOfBirth.ToString(), ProfilePicture = data };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
为了与用户交互我使用了下面的View,这段代码的底部是添加ProfilePicture的部分。
@model StudentBookApp.Models.ExtendedIdentityModels
@{
ViewBag.Title = "Register";
}
@*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>*@
<link href="~/Content/datepicker.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control " })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.City, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.DateOfBirth, new { @class = "datepicker form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ProfilePicture, new { @class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserProfilePicture, new {type = "file"})
@Html.ValidationMessage("CustomMessage")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker();
})
</script>
几乎一切顺利,但对于 model.UserProfilePicture 我得到空值。由于某种原因,它没有从 View 获得通过。我做错了什么?我被困了几个小时试图找到可能的错误,但没有成功。这种用于将图像插入 table 的 'mechanism' 在 MVC 4 中使用效果很好...有人看到我遗漏了什么以及这种方法有什么问题吗?
与 MVC 或 c# 无关,它是 HTML ;) /edit 还要感谢您提供问题中的所有细节,因为它非常详尽。
您的表单需要 enctype="multipart/form-data"
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype="multipart/form-data" }))
public ActionResult AddImage(Brand model,HttpPostedFileBase image1)
{
var db = new H_Cloths_SaloonEntities();
if (image1!=null)
{
model.Brandimage = new byte[image1.ContentLength];
image1.InputStream.Read(model.Brandimage,0,image1.ContentLength);
}
db.Brands.Add(model);
db.SaveChanges();
ViewBag.Path = "image uploaded Successfully...!";
return View(model);
}
我正在尝试使用 ASP.NET MVC 和 Entity Framework 将图像添加到数据库 table。
我已经对名为 'AspNetUsers' 的现有 ASP.NET MVC table 进行了迁移,并在其中添加了一些新列。
其中一列是ProfilePicture,是byte[]类型。
当我尝试注册新用户时,我希望用户提供其个人资料图片以及其他数据。
这是具有新添加属性的 ApplicationUser class:
public class ApplicationUsers : IdentityUser
{
public string Name { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string DateOfBirth { get; set; }
public byte[] ProfilePicture { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUsers> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
为了将图像放入 table,我使用了名为 ExtendedIdentityModels 的 class 包装器。这个class继承自RegisterViewModelclass,它只有一个属性 UserProfilePicture,类型为HttpPostedFileBase,用于从用户页面获取图像。
public class ExtendedIdentityModels : RegisterViewModel
{
public HttpPostedFileBase UserProfilePicture { get; set; }
}
我更改了控制器中的 Register 方法以将此新属性添加到数据库中:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(ExtendedIdentityModels model)
{
if (ModelState.IsValid)
{
if (model.UserProfilePicture != null)
{
if (model.UserProfilePicture.ContentLength > (4 * 1024 * 1024))
{
ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
return View();
}
if (!(model.UserProfilePicture.ContentType == "image/jpeg" || model.UserProfilePicture.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
}
}
byte[] data = new byte[model.UserProfilePicture.ContentLength];
model.UserProfilePicture.InputStream.Read(data, 0, model.UserProfilePicture.ContentLength);
var user = new ApplicationUsers() { UserName = model.Email, Email = model.Email, Name = model.Name, LastName = model.LastName, City = model.City, DateOfBirth = model.DateOfBirth.ToString(), ProfilePicture = data };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
为了与用户交互我使用了下面的View,这段代码的底部是添加ProfilePicture的部分。
@model StudentBookApp.Models.ExtendedIdentityModels
@{
ViewBag.Title = "Register";
}
@*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>*@
<link href="~/Content/datepicker.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control " })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.City, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.DateOfBirth, new { @class = "datepicker form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ProfilePicture, new { @class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserProfilePicture, new {type = "file"})
@Html.ValidationMessage("CustomMessage")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker();
})
</script>
几乎一切顺利,但对于 model.UserProfilePicture 我得到空值。由于某种原因,它没有从 View 获得通过。我做错了什么?我被困了几个小时试图找到可能的错误,但没有成功。这种用于将图像插入 table 的 'mechanism' 在 MVC 4 中使用效果很好...有人看到我遗漏了什么以及这种方法有什么问题吗?
与 MVC 或 c# 无关,它是 HTML ;) /edit 还要感谢您提供问题中的所有细节,因为它非常详尽。
您的表单需要 enctype="multipart/form-data"
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype="multipart/form-data" }))
public ActionResult AddImage(Brand model,HttpPostedFileBase image1)
{
var db = new H_Cloths_SaloonEntities();
if (image1!=null)
{
model.Brandimage = new byte[image1.ContentLength];
image1.InputStream.Read(model.Brandimage,0,image1.ContentLength);
}
db.Brands.Add(model);
db.SaveChanges();
ViewBag.Path = "image uploaded Successfully...!";
return View(model);
}