[英]How to save image in database and display it into Views in MVC 4?
我有一張像以下一樣的表格:
CREATE TABLE [dbo].[tblA]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[fname] NVARCHAR(50) NULL,
[lname] NVARCHAR(50) NULL,
[imageUrl] NVARCHAR(50) NULL
)
我想用文件上傳來上傳文件。 如何在數據庫中保存圖像並將其顯示到視圖中?
家庭控制器:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace test2.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult FileUpload(HttpPostedFileBase file) { if (file != null) { Database1Entities db = new Database1Entities(); string ImageName = System.IO.Path.GetFileName(file.FileName); string physicalPath =Server.MapPath("~/images/"+ ImageName); // save image in folder file.SaveAs(physicalPath); //save new record in database tblA newRecord = new tblA(); newRecord.fname = Request.Form["fname"]; newRecord.lname = Request.Form["lname"]; newRecord.imageUrl = ImageName; db.tblAs.Add(newRecord); db.SaveChanges(); } //Display records return RedirectToAction("../home/Display/"); } public ActionResult Display() { return View(); } } }
索引視圖
@{ ViewBag.Title = "Index"; } @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div> First name<br /> @Html.TextBox("fname") <br /> Last name<br /> @Html.TextBox("lname") <br /> Image<br /> <input type="file" name="file" id="file" style="width: 100%;" /> <br /> <input type="submit" value="Upload" class="submit" /> </div> }
顯示視圖
@{ ViewBag.Title = "Display"; } @{ test2.Database1Entities db = new test2.Database1Entities(); } @using (Html.BeginForm()) { <table border="1"> <thead> <tr> <th>Image</th> <th>First name</th> <th>Last name</th> </tr> </thead> <tbody> @foreach (var item in db.tblAs) { <tr> <td><img src="~/images/@item.imageUrl" width="100" height="100" /></td> <td>@item.fname</td> <td>@item.lname</td> </tr> } </tbody> </table> }
輸出:
/家/
/家庭/顯示/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.