2012-03-27 42 views
1

我有存儲在數據庫中的頭像。我已經使用數據類型圖像的化身。我想將用戶的頭像加載到圖像控件中,但我無法使其工作。我曾嘗試這個代碼沒有任何的運氣:從SQL數據庫asp.net加載圖片C#

public void GetUserAvatar() 
    { 
     string username = Convert.ToString(Session["username"]); 

     var image = from u in dc.Users 
        where u.username == username 
        select u.image; 
     imgAvatar.Controls.Add(image); 
    } 

我想我可能不得不將圖像保存到一個文件夾,然後將文件保存路徑數據庫來代替。這似乎更容易,更順暢。有任何想法嗎?

我最終將圖像保存到文件夾,然後將路徑保存到數據庫。我對圖片上傳的代碼現在看起來是這樣的:

public void addImage() 
    { 
     if (fuAvatar.PostedFile.ContentType.ToLower().StartsWith 
      ("image") && fuAvatar.HasFile) 
     { 
      string saveLocation = Server.MapPath("savedAvatars/"); 
      string fileExtension = System.IO.Path.GetExtension(fuAvatar.FileName); 
      string fileName = Convert.ToString(Session["userid"]); 
      string savePath = saveLocation + fileName + fileExtension; 
      fuAvatar.SaveAs(savePath); 

      string imageDBPath = fileName + fileExtension; 

      LinqClass1DataContext dc = new LinqClass1DataContext(); 
      int userid = Convert.ToInt32(Session["userid"]); 
      var tblUser = (from u in dc.Users 
          where u.userid == userid 
          select u).First(); 
      tblUser.imagePath = @"\savedAvatars\"+imageDBPath; 
      dc.SubmitChanges(); 
      lblResult.Text = "Avatar lastet opp!"; 
     } 
     else lblResult.Text = "Avatar ikke lastet opp!"; 
    } 

並加載圖片:

public void GetUserAvatar() 
    { 
     int userid = Convert.ToInt32(Session["userid"]); 

     var varPath = dc.Users.Single(u => (u.userid == userid)).imagePath; 

     string imagePath = Convert.ToString(varPath); 
     imgAvatar.ImageUrl = imagePath; 
    } 
+1

爲什麼要將實際圖像存儲在數據庫中?當然存儲文件路徑會更好? – 2012-03-27 08:40:10

+0

http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Curt 2012-03-27 08:49:07

回答

3

你應該增加一個通用的處理程序文件(.ashx的)和它類似的東西寫:

string sql = "select image from table1"; 
SqlCommand command = new SqlCommand(sql, con); 
SqlDataReader dReader = command.ExecuteReader(); 
dReader.Read(); 
context.Response.BinaryWrite((byte[])dReader["Source"]); 
dReader.Close(); 

然後在頁面中做這樣的事情:

img.ImageUrl = "Handler.ashx; 
+0

我必須在這個文件中創建一個新的方法,或者我可以使用公共無效ProcessRequest(HttpContext上下文)? – Twistar 2012-03-27 09:12:23

+0

你不需要創建一個新的方法,實際上你應該使用ProcessRequest方法:) – 2012-03-27 09:17:39

+0

更多的信息可以在這裏找到:http://www.codeproject.com/Articles/33310/C-Save-and -Load-圖像從 - 數據庫 – lko 2012-11-30 11:32:22