asp.net上传图片到数据库。
use System.IO;
#region 上传和显示图片,存于数据库中
/// <summary>
/// 图片保存至数据库函数
/// site http://www.jb200.com
/// </summary>
/// <param name="filePath">图片绝对路径</param>
private void SaveImg(string filePath) {
SqlConnection Conn=null;
//保存图片到数据库
Conn=new SqlConnection("Data Source=127.0.0.1;Initial Catalog=CTS;User id=sa;Password=as;");
try{
SqlCommand Cmd=new SqlCommand("update BM_Clerk set Test=@a where ClerkID <= 40 ",Conn);
FileStream mystream=new FileStream(filePath,FileMode.Open,FileAccess.Read); //读取文件到流中
long len=mystream.Length;
Cmd.Parameters.Add("@a",SqlDbType.Image);
Cmd.Parameters["@a"].Direction=System.Data.ParameterDirection.Input;
byte[] box=new byte[len];
mystream.Read(box,0,(int)len);
Cmd.Parameters["@a"].Value=box;
//更新
Conn.Open();
Cmd.ExecuteNonQuery();
mystream.Close();
}
finally {
Conn.Close();
}
}
/// <summary>
/// 数据库中读取图片
/// </summary>
private void ShowImg()
{
try {
SqlConnection Conn=new SqlConnection("Data Source=127.0.0.1;Initial Catalog=CTS;User id=sa;Password=as;");
Conn.Open();
SqlCommand Cmd=new SqlCommand("select * from BM_Clerk",Conn);
SqlDataReader myrd = Cmd.ExecuteReader();
if(myrd.Read()) {
//读取图片
if(!myrd.IsDBNull(1)) {
byte[] box=(byte [])myrd["Test"];
//构造流
Stream stream1=new MemoryStream(box);
this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);
stream1.Close();
}
else {
MessageBox.Show("该字段是NULL");
}
}
Conn.Close();
}
catch(Exception my) {
MessageBox.Show(my.Message.ToString());
}
}
#endregion