Asp.Net在SqlServer中的圖片存取技術

在使用asp.net將圖片上傳並存入SqlServer中,而後從SqlServer中讀取並顯示出來數據庫

一,上傳並存入SqlServer
 數據庫結構
  create table test
  {
     id identity(1,1),
     FImage p_w_picpath
  }
  相關的存儲過程
  Create proc UpdateImage
  (
     @UpdateImage Image
  )
  As
  Insert Into test(FImage) values(@UpdateImage)
  GO
app

在UpPhoto.aspx文件中添加以下:
<input id="UpPhoto" name="UpPhoto" runat="server" type="file">
<asp:Button id="btnAdd" name="btnAdd" runat="server" Text="上傳"></asp:Button>
asp.net

而後在後置代碼文件UpPhoto.aspx.cs添加btnAdd按鈕的單擊事件處理代碼:
private void btnAdd_Click(object sender, System.EventArgs e)
{
        //得到圖象並把圖象轉換爲byte[]
        HttpPostedFile upPhoto=UpPhoto.PostedFile;
        int upPhotoLength=upPhoto.ContentLength;
        byte[] PhotoArray=new Byte[upPhotoLength];
        Stream PhotoStream=upPhoto.InputStream;
        PhotoStream.Read(PhotoArray,0,upPhotoLength);
ide

        //鏈接數據庫
        SqlConnection conn=new SqlConnection();
        conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";
post

        SqlCommand cmd=new SqlCommand("UpdateImage",conn);
        cmd.CommandType=CommandType.StoredProcedure;
.net

        cmd.Parameters.Add("@UpdateImage",SqlDbType.Image);
        cmd.Parameters["@UpdateImage"].Value=PhotoArray;
server

        //若是你但願不使用存儲過程來添加圖片把上面四句代碼改成:
        //string strSql="Insert into test(FImage) values(@FImage)";
        //SqlCommand cmd=new SqlCommand(strSql,conn);
        //cmd.Parameters.Add("@FImage",SqlDbType.Image);
        //cmd.Parameters["@FImage"].Value=PhotoArray;
事件

conn.Open();
 cmd.ExecuteNonQuery();
 conn.Close();
}
圖片

二,從SqlServer中讀取並顯示出來
在須要顯示圖片的地方添加以下代碼:
<asp:p_w_picpath id="imgPhoto" runat="server" ImageUrl="ShowPhoto.aspx"></asp:p_w_picpath>
input

ShowPhoto.aspx主體代碼: private void Page_Load(object sender, System.EventArgs e) {      if(!Page.IsPostBack)      {                 SqlConnection conn=new SqlConnection()                 conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";                  string strSql="select * from test where id=2";//這裏假設獲取id爲2的圖片                 SqlCommand cmd=new SqlCommand()                 reader.Read();                 Response.ContentType="application/octet-stream";                 Response.BinaryWrite((Byte[])reader["FImage"]);                 Response.End();                 reader.Close();      } }

相關文章
相關標籤/搜索