上傳圖片到SQL SERVER 存為IMAGE類型的
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile post = imgInput.PostedFile;
int lent = post.ContentLength;
byte []lentimg=new byte[lent];
Stream photostream = post.InputStream;
photostream.Read(lentimg, 0, lent);
SqlCommand sqlcom = new SqlCommand("insert into zhaoxiaomingPIC values(@img)",con);
sqlcom.Parameters.Add("@img", SqlDbType.Image);
sqlcom.Parameters["@img"].Value = lentimg;
con.Open();
sqlcom.ExecuteNonQuery();
con.Close();
}
從資料庫為IMAGE類型的表中讀資料
//WEB部分
string str =ConfigurationSettings.AppSettings["connString"].ToString();
SqlConnection con = new SqlConnection(str);
string sql= "select personimage,personImagetype from person where personEmail='"+Session["email"]+"'";
SqlCommand cmd= new SqlCommand(sql,con);
con.Open();
SqlDataReader dr=cmd.ExecuteReader();
Byte[] PictureData =null;
while(dr.Read())
{
PictureData =(Byte[])dr[0];
Response.ContentType=dr[1].ToString();
}
this.EnableViewState=false;
Response.AppendHeader("contect-length",PictureData.Length.ToString());
Response.BinaryWrite(PictureData);
Response.End();
//上部分的代碼寫了一個show.asp頁面裡,
//在調用的頁面裡載入一個image控制項就可以了,
//調用代碼為:this.Image1.ImageUrl="show.aspx";
//WINFROM部分
string strCon="data source=aaaa;initial catalog=school;uid=sa;pwd=";
SqlConnection con = new SqlConnection(strCon);
con.Open();
string sql="select personimage from person where personID="+this.textBox1.Text+"";
SqlCommand cmd=new SqlCommand(sql,con);
SqlDataReader dr=cmd.ExecuteReader();
if(dr.HasRows)
{
dr.Read();
byte[] img=(byte[])dr["personimage"];
MemoryStream ms=new MemoryStream();
ms.Write(img,0,img.Length);
this.pictureBox1.Image=Image.FromStream(ms);
ms.Close();
}
dr.Close();