我有存儲在數據庫中的頭像。我已經使用數據類型圖像的化身。我想將用戶的頭像加載到圖像控件中,但我無法使其工作。我曾嘗試這個代碼沒有任何的運氣:從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;
}
爲什麼要將實際圖像存儲在數據庫中?當然存儲文件路徑會更好? – 2012-03-27 08:40:10
http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Curt 2012-03-27 08:49:07