数据库读取和保存图片

//从数据库读取图片,并保存为11.jpg
using (SqlConnection vConn = new SqlConnection(mConnStr))
{
vConn.Open();
using (SqlCommand vCmd = new SqlCommand("select picture from tbUsers", vConn))
{
SqlDataReader dr = vCmd.ExecuteReader();
if (dr.Read())
{
byte[] photo = dr[0] as byte[];
FileStream fs = new FileStream(Server.MapPath("~/11.jpg"), FileMode.CreateNew);
fs.Write(photo, 0, photo.Length);
fs.Close();
}
dr.Close();
}
}
//保存图片到数据库
FileStream fs = new FileStream(@"E:\1.jpg", FileMode.Open, FileAccess.Read);
BinaryReader rd = new BinaryReader(fs);
byte[] vPhoto = rd.ReadBytes((int)fs.Length);
rd.Close();
fs.Close();
using (SqlConnection vConn = new SqlConnection(mConnStr))
{
vConn.Open();
using (SqlCommand vCmd = new SqlCommand("insert into tbusers(username,picture) values(@username,@picture)", vConn))
{
vCmd.Parameters.Add(new SqlParameter("@username", "张三"));
vCmd.Parameters.Add(new SqlParameter("@picture", vPhoto));
vCmd.ExecuteNonQuery();
}
}

你可能感兴趣的:(Asp.Net)