我試圖添加一個圖像到數據庫表使用ASP.NET MVC與實體框架。在ASP.NET MVC中添加圖像到數據庫5
我已經對名爲'AspNetUsers'的現有ASP.NET MVC表進行了遷移,並在其中添加了一些新列。
其中一列是ProfilePicture,它是byte []類型。
當我試圖註冊新用戶時,我期待該用戶提供其他數據中的個人資料圖片。
這裏是ApplicationUser類新增加的屬性:
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;
}
}
以獲取圖像到表中我使用的是名爲ExtendedIdentityModels類包裝。該類繼承自RegisterViewModel類,它只有一個屬性UserProfilePicture,類型爲HttpPostedFileBase,用於從用戶頁面獲取圖像。
public class ExtendedIdentityModels : RegisterViewModel
{
public HttpPostedFileBase UserProfilePicture { get; set; }
}
我已經改變了註冊方法在控制這一新的屬性添加到數據庫:
[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);
}
對於我用下面查看用戶交互,這個代碼的底部是一個部分添加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。我做錯了什麼?我一直堅持幾個小時試圖找到可能的錯誤,但沒有成功。這種用於插入圖像的「機制」用於在MVC 4中很好地工作...有人看到我失去了什麼,這種方法有什麼問題嗎?
這是一些真棒C#,MVC,和剃刀。我希望我知道如何使用你所做的一切。 – jp2code