我将头像存储在数据库中。我已经使用了数据类型图像作为头像。我想将用户的头像加载到图像控件中,但我不能让它工作。我没有运气就试过这段代码:
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;
}
答案 0 :(得分: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;
答案 1 :(得分:0)
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129首先我发现了这篇文章。基本上你需要创建一个响应原始图像的处理程序。
答案 2 :(得分:0)