【发布时间】:2018-10-16 13:48:08
【问题描述】:
我想在页面加载时在图像控件中显示图像。我正在使用以下代码。我的问题是图片作为二进制数据保存在数据库中,但是无法在图片控件中检索到图片
public partial class TeacherProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
profilepic();
}
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
Byte[] imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "' where id ='" + idd.Text + "' ", con);
//cmd.Parameters.AddWithValue("@userid", 222); //image id
//cmd.Parameters.AddWithValue("@pic", imgbyte);
//try
//{
con.Close();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image Uploaded";
con.Close();
//}
//catch
//{
// Label1.Text = "Try Again";
//}
}
}
public void profilepic()
{
SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
//cmd2.Parameters.AddWithValue("@userid", username1.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[])dr["Photo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
cmd2.ExecuteNonQuery();
con.Close();
}
else
{
}
}
}
有人可以帮帮我吗?
提前谢谢...
【问题讨论】:
-
Photo列的类型是什么,是 varbinary 吗? -
没有它的数据类型是图像
-
表中的字节是否正确更新?我猜他们更新此字段的方式不正确。看看这个答案stackoverflow.com/a/17856781/1433093。获取该数据并将其传递到图像控件中对我来说似乎很好。
-
SQL Injection alert - 您应该不将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables
标签: asp.net sql-server image image-conversion