2012-03-07 74 views
2

我已經通過幾乎每個帖子在這個網站上,它似乎處理圖像上傳&持久性到SQL Server數據庫但是,我正在做的事情仍然是不正確的。保存/顯示圖像在asp.net MVC

圖像無法正確保存或從數據庫中正確提取字節正在寫入/檢索圖像無效。當比較上傳到原始圖像的尺寸時,尺寸是不同的(更大)?

型號

public byte[] Photo { get; set; } 
public string PhotoMimeType { get; set; } 
public string PhotoName { get; set; } 

Sql Server的

[PhotoMimeType] [nvarchar](50) NULL, 
[PhotoName] [nvarchar](50) NULL, 
[Photo] [image] NULL, 

內的控制器我有以下保存圖像

public ActionResult Edit(AgentInfo modifiedAgent, HttpPostedFileBase postedFile) 
{ 
    if(ModelState.IsValid) 
    { 
     var model = _agentRepository.GetByID(modifiedAgent.AgentID); 
     if (TryUpdateModel(model)) 
     { 
      if (postedFile != null) 
      { 
       int imageLength = postedFile.ContentLength; 
       byte[] imgBytes = new byte[imageLength]; 
       postedFile.InputStream.Read(imgBytes, 0, imageLength); 

       model.PhotoMimeType = postedFile.ContentType; 
       model.PhotoName = postedFile.FileName; 
       model.Photo = imgBytes; 
      } 
      _agentRepository.Save(model); 
      return RedirectToAction("ManageAgents", "Agent"); 
     } 
    } 

    return View("Edit", modifiedAgent); 
} 

檢索

[HttpGet] 
public ActionResult GetImage(int id) 
{ 
    var agent = _agentRepository.GetByID(id); 
    return File(agent.Photo, agent.PhotoMimeType, agent.PhotoName); 
} 

顯示

<img src='@Url.Action("GetImage", "Agent", new { id = Model.AgentID })' /> 

編輯:

認爲它是與我是如何接線此一起它變成一個問題後好成爲我的數據庫映射..... frick

據透露,以流暢,NHibernate的映射,並要保存圖像字節時,SQL數據類型是VARBINARY(最多)以下映射:

Map(x => x.Photo).Column("Photo").Length(2147483647).CustomSqlType("varbinary(MAX)"); 

回答

4

儘量只閱讀它之前倒帶的InputStream:

postedFile.InputStream.Position = 0; 

或使用臨時MemoryStream

using (var memoryStream = new MemoryStream()) 
{ 
    postedFile.InputStream.CopyTo(memoryStream); 
    model.Photo = memoryStream.ToArray(); 
} 
+0

謝謝,達林通過這兩個選項會照顧你,只要它使我更深的挖掘,我發現了WA問題在我流利的nhibernate映射中 – Jesse 2012-03-07 17:32:31