上傳圖片到SQL SERVER

來源:互聯網
上載者:User
上傳圖片到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();

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.