2013-07-09 188 views
2

我試圖在MVC4 web應用程序上創建用戶配置文件頁面。MVC4從SQL Server表格檢索圖像文件到html圖像

在userprofile頁面上有一個圖像<img />標籤來顯示個人資料照片。在圖像下方,有「瀏覽」,「上傳」按鈕供用戶瀏覽和上傳照片。點擊上傳按鈕後,它應該將照片上傳到SQL Server並在配置文件頁面上顯示圖像。

我可以上傳照片並保存到SQL Server表中。現在我想從SQL Server表中檢索照片到配置文件頁面。

這裏是我的用戶個人資料頁/.cshtml頁(Razor視圖)

@model MvcSamples.Models.UserPicModel 

@{ 

    ViewBag.Title = "PersonalInfo"; 
} 

<h2>PersonalInfo</h2> 

<form action="/UserDetails/PersonalInfo" method="post" enctype="multipart/form-data"> 
     <img src="" alt="ProfilePhoto" /> 
    <label for="photo">Photo:</label> 
    <input type="file" name="photo" id="photo" /> 
    <input type="submit" value="Upload" /> 

</form> 

這是我使用的檢索照片從SQL Server表背的代碼。請注意,照片是從DB作爲byte[]

byte[] barrImg = usr.GetProfilePhoto(id); 

當我調試,我可以看到照片被檢索到「barImg」檢索。

我的問題1:從這裏我怎樣才能得到這<img src="" alt="ProfilePhoto" />,這樣它會顯示在個人資料頁面上的實際照片?

問題2:有人能提出任何更好的替代方案建議/樣品/指針來實現,涉及的Jquery /阿賈克斯相同的功能/ JavaScript的

預先感謝您

回答

3

您可以使用FileResult,送二進制數據到響應。

public FileResult GetProfileImage(int id) 
{ 
    var usr = new Whatever(); 
    byte[] barrImg = usr.GetProfilePhoto(id); 
    return File(barrImg, "image/png"); 
} 

你可以使用它作爲,

<img src="@Url.Action("GetProfileImage", "Controller", new { id = 5})" 
+0

是的,這個工作 – Steve