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

來源:互聯網
上載者:User
asp.net|server|sqlserver|上傳|顯示

1,使用asp.net將圖片上傳並存入SqlServer中,然後從SqlServer中讀取並顯示出來
一,上傳並存入SqlServer
 資料庫結構
  create table test
  {
     id identity(1,1),
     FImage image
  }
  相關的預存程序
  Create proc UpdateImage
  (
     @UpdateImage Image
  )
  As
  Insert Into test(FImage) values(@UpdateImage)
  GO
在UpPhoto.aspx檔案中添加如下:
<input id="UpPhoto" name="UpPhoto" runat="server" type="file">
<asp:Button id="btnAdd" name="btnAdd" runat="server" Text="上傳"></asp:Button>

然後在後置代碼檔案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);

        //串連資料庫
        SqlConnection conn=new SqlConnection();
        conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";

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

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

        //如果你希望不使用預存程序來添加圖片把上面四句代碼改為:
        //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:image id="imgPhoto" runat="server" ImageUrl="ShowPhoto.aspx"></asp:image>

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();
     }
}


3,在winform中將圖片存入sqlserver,並從sqlserver中讀取並顯示在picturebox中

1,存入sqlserver
資料庫結構和使用的儲存過過程,同上面的一樣
 1.1,在表單中加一個OpenFileDialog控制項,命名為ofdSelectPic
 1.2,在表單上添加一個開啟檔案按鈕,添加如下單擊事件代碼:
    Stream ms;
  byte[] picbyte;
  //ofdSelectPic.ShowDialog();
  if (ofdSelectPic.ShowDialog()==DialogResult.OK)
  {
   if ((ms=ofdSelectPic.OpenFile())!=null)
   {
    //MessageBox.Show("ok");
    picbyte=new byte[ms.Length];
    ms.Position=0;
    ms.Read(picbyte,0,Convert.ToInt32(ms.Length));
    //MessageBox.Show("讀取完畢!");

    //串連資料庫
    SqlConnection conn=new SqlConnection();
    conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";

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

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

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

    ms.Close();
    }
   }

2,讀取並顯示在picturebox中
 2.1 添加一個picturebox,名為ptbShow
 2.2 添加一個按鈕,添加如下響應事件:
      SqlConnection conn=new SqlConnection();
 conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";

 string strSql="select FImage from test where id=1";

 SqlCommand cmd=new SqlCommand(strSql,conn);

 conn.Open();
 SqlDataReader reader=cmd.ExecuteReader();
        reader.Read();

 MemoryStream ms=new MemoryStream((byte[])reader["FImage"]);


 Image image=Image.FromStream(ms,true);

        reader.Close();
        conn.Close();

 ptbShow.Image=image;


在UpPhoto.aspx檔案中添加如下:
<input id="UpPhoto" name="UpPhoto" runat="server" type="file">
<asp:Button id="btnAdd" name="btnAdd" runat="server" Text="上傳"></asp:Button>

然後在後置代碼檔案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);

        //串連資料庫
        SqlConnection conn=new SqlConnection();
        conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";

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

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

        //如果你希望不使用預存程序來添加圖片把上面四句代碼改為:
        //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:image id="imgPhoto" runat="server" ImageUrl="ShowPhoto.aspx"></asp:image>

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();
     }
}


3,在winform中將圖片存入sqlserver,並從sqlserver中讀取並顯示在picturebox中

1,存入sqlserver
資料庫結構和使用的儲存過過程,同上面的一樣
 1.1,在表單中加一個OpenFileDialog控制項,命名為ofdSelectPic
 1.2,在表單上添加一個開啟檔案按鈕,添加如下單擊事件代碼:
    Stream ms;
  byte[] picbyte;
  //ofdSelectPic.ShowDialog();
  if (ofdSelectPic.ShowDialog()==DialogResult.OK)
  {
   if ((ms=ofdSelectPic.OpenFile())!=null)
   {
    //MessageBox.Show("ok");
    picbyte=new byte[ms.Length];
    ms.Position=0;
    ms.Read(picbyte,0,Convert.ToInt32(ms.Length));
    //MessageBox.Show("讀取完畢!");

    //串連資料庫
    SqlConnection conn=new SqlConnection();
    conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";

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

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

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

    ms.Close();
    }
   }

2,讀取並顯示在picturebox中
 2.1 添加一個picturebox,名為ptbShow
 2.2 添加一個按鈕,添加如下響應事件:
      SqlConnection conn=new SqlConnection();
 conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";

 string strSql="select FImage from test where id=1";

 SqlCommand cmd=new SqlCommand(strSql,conn);

 conn.Open();
 SqlDataReader reader=cmd.ExecuteReader();
        reader.Read();

 MemoryStream ms=new MemoryStream((byte[])reader["FImage"]);


 Image image=Image.FromStream(ms,true);

        reader.Close();
        conn.Close();

 ptbShow.Image=image;

 



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.