2017-02-27 79 views
-4

我有一個表像下如何在數據庫中保存圖像並將其顯示到MVC 5中的視圖中?

CREATE TABLE [dbo].[Movies] (
[fname] NVARCHAR(50) NULL, 
[lname] NVARCHAR(50) NULL, 
[MoviePoster] VARCHAR (50) NULL, 

如何圖像保存到電影海報領域,以及如何查看它

+0

你可以看看我的答案,關於對[如何在MVC顯示圖片](HTTP此問題://計算器。 com/questions/30651531/how-to-display-images-in-mvc/30653266#30653266)和[上傳文件前的預覽圖像](http://stackoverflow.com/questions/9092723/preview-image-before-uploading -file/29036150#29036150)。 –

回答

-1
  1. 在Solution Explorer中創建一個「Images」文件夾。
  2. 創建一個ADO.NET實體數據模型(本例中爲 「Database1Entities」)

家庭控制器

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.MoviePoster = 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>  
} 

DisplayView

@{ 
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> 
} 

輸出將與觀看圖像的表從數據庫

0
[MoviePoster]  [varbinary](max) NULL 

- 你必須插入圖像作爲BLOB - 插入BLOB腳本:在視圖中

INSERT INTO [Movies](MoviePoster) 
VALUES (SELECT * FROM OPENROWSET (BULK 'your img url', SINGLE_BLOB)) 

├27類顯示器的圖像:

<img src='data:image/jpeg;base64, <--data from db-->' /> 
0

如何在服務器上保存電影的海報讓我們說:

/content/images/movieposters/thearrival.jpg 

和存儲MoviePoster場僅文件名thearrival.jpg

我個人比較喜歡這種做法,因爲如果讓我們說你的數據庫會增長你將有更多的訪問者......好吧,您將能夠將所有電影海報移動到不同的服務器上,並從應用程序服務器釋放大量負載。