现在的位置: 首页 > 综合 > 正文

上传图片到SQL SERVER

2013年10月14日 ⁄ 综合 ⁄ 共 1718字 ⁄ 字号 评论关闭
上传图片到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();

 

抱歉!评论已关闭.