[英]how to pass image to database with user object in asp.net mvc
模型是用戶:
public class Users
{
[Key]
public int UserId { get; set; }
[Required]
public string Firstname { get; set; }
public string Lastname { get; set; }
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public string UserImage { get; set; }
}
在用戶控制器中創建ActionMethod:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UserId,Firstname,Lastname,Username,Password,UserImage")] Users users)
{
if (ModelState.IsValid)
{
db.Users.Add(users);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(users);
}
最后,Create視圖如下所示:
@model WebApplication2.Models.Users
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Users</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Firstname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Firstname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Lastname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Lastname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Lastname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UserImage, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="UserImage" value="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
所以請幫助我,我該怎么做?我嘗試了很多但失敗了的用戶對象,將圖像名稱傳遞給數據庫。
不要使用EF中的實體類在視圖和操作方法之間傳輸數據。 您應該創建一個視圖模型。 您可以為HttpPostedFileBase
類型的UserImage添加一個屬性。
public class CreateUserVm
{
public int UserId { get; set; }
[Required]
public string Firstname { get; set; }
public string Lastname { get; set; }
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public HttpPostedFileBase UserImage { get; set; }
}
現在,在GET中,確保發送此CreateUserVm類的對象。
public ActionResult Create()
{
return View(new CreateUserVm());
}
並且您的創建視圖將強類型於該視圖模型。
@model YourNameSpaceHere.CreateUserVm
@using (Html.BeginForm("Create", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(false)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name,
"", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UserImage, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="UserImage" />
</div>
</div>
<input type="submit" />
}
並且在HttpPost操作中,該操作接受我們的CreateUserVm視圖模型的對象作為參數。 您可以使用唯一的名稱將文件保存在磁盤中,並將其與用戶記錄相關聯,以供以后檢索。
[HttpPost]
public ActionResult Create(CreateUserVm model)
{
if(ModelState.IsValid)
{
// Posted file is available at model.UserImage property. You may save it to somewhere.
// Quick Example of saving to disk
var fName= Path.GetFileName(model.UserImage.FileName);
fName = fName.Replace(" ", "_");
fName = Guid.NewGuid().ToString()+fName;
model.UserImage.SaveAs("~/"+fName);
var u = new Users { Firstname = model.FirstName, Lastname=model.LastName };
u.Password=model.Password;
u.UserImage= fName;
db.Users.Add(u);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
好的,您需要做一些事情來完成這項工作。 首先,您需要在視圖中更改表單類型,以向服務器指示文件即將發送:
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
//Form Stuff here
}
然后,在控制器端,您需要通過添加類型HttpPostedFileBase
類型的UserImage
來告訴服務器期望發布請求中的文件:
public ActionResul Upload([Bind(Include = "UserId,Firstname,Lastname,Username,Password")] Users users, HttpPostedFileBase UserImage)
{
//Controller Logic
}
現在,您的視圖正在發送圖像,而控制器正在接受圖像...現在,我們需要解決在數據庫中存儲圖像的概念。 您可以通過將上載的圖像(現在存儲在UserImage
變量中)轉換為字節數組(此過程未在我的文章中顯示, 但在此處進行了描述 ),然后將Users
模型中的屬性更改為:
public string UserImage { get; set; }
到以下內容:
public byte[] UserImage { get; set; }
但是,出於某些原因,我建議您不要這樣做...相反,我建議您執行以下操作:
yoursite.com/Users/ProfileImage/{UserID}
)中創建一個端點(操作方法),以檢索圖像 <img src="/Users/ProfileImages/1"> User Image</img>
,它將加載正確的用戶圖像。 我不會為您概述上述工作流程的每個步驟,但是通常這就是您描述的用例的處理方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.