程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> 在SQLServer中保存和輸出圖片

在SQLServer中保存和輸出圖片

編輯:關於SqlServer
在SQL Server中保存和輸出圖片

cashcho(翻譯)

關鍵字 SQL Server images

出處 http://www.bipinjoshi.com/

介紹

  有時候我們需要保存一些binary data進數據庫。SQL Server提供一個叫做image的特殊數據類型供我們保存binary data。Binary data可以是圖片、文檔等。在這篇文章中我們將看到如何在SQL Server中保存和輸出圖片。

建表

  為了試驗這個例子你需要一個含有數據的table(你可以在現在的庫中創建它,也可以創建一個新的數據庫),下面是它的結構:

Column Name Datatype Purpose ID Integer identity column Primary key
IMGTITLE Varchar(50) Stores some user frIEndly title to identity the image IMGTYPE Varchar(50) Stores image content type. This will be same as recognized content types of ASP.Net
IMGDATA Image Stores actual image or binary data.
保存images進SQL Server數據庫

  為了保存圖片到table你首先得從客戶端上傳它們到你的web服務器。你可以創建一個web form,用TextBox得到圖片的標題,用Html File Server Control得到圖片文件。確信你設定了Form的encType屬性為multipart/form-data。

Stream imgdatastream = File1.PostedFile.InputStream;

int imgdatalen = File1.PostedFile.ContentLength;

string imgtype = File1.PostedFile.ContentType;

string imgtitle = TextBox1.Text;

byte[] imgdata = new byte[imgdatalen];

int n = imgdatastream.Read(imgdata,0,imgdatalen);

string connstr=

((NameValueCollection)Context.GetConfig

("aPPSettings"))["connstr"];

SqlConnection connection = new SqlConnection(connstr);

SqlCommand command = new SqlCommand

("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)

VALUES ( @imgtitle, @imgtype,@imgdata )", connection );

SqlParameter paramTitle = new SqlParameter

("@imgtitle", SqlDbType.VarChar,50 );

paramTitle.Value = imgtitle;

command.Parameters.Add( paramTitle);

SqlParameter paramData = new SqlParameter

( "@imgdata", SqlDbType.Image );

paramData.Value = imgdata;

command.Parameters.Add( paramData );

SqlParameter paramType = new SqlParameter

( "@imgtype", SqlDbType.VarChar,50 );

paramType.Value = imgtype;

command.Parameters.Add( paramType );

connection.Open();

int numRowsAffected = command.ExecuteNonQuery();

connection.Close();


從數據庫中輸出圖片

  現在讓我們從數據庫中取出我們剛剛保存的圖片,在這兒,我們將直接將圖片輸出至浏覽器。你也可以將它保存為一個文件或做任何你想做的。

private void Page_Load(object sender, System.EventArgs e)

{

string imgid =Request.QueryString["imgid"];

string connstr=((NameValueCollection)

Context.GetConfig("aPPSettings"))["connstr"];

string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = "

+ imgid;

SqlConnection connection = new SqlConnection(connstr);

SqlCommand command = new SqlCommand(sql, connection);

connection.Open();

SqlDataReader dr = command.ExecuteReader();

if(dr.Read())

{

Response.ContentType = dr["imgtype"].ToString();

Response.BinaryWrite( (byte[]) dr["imgdata"] );

}

connection.Close();

}



  在上面的代碼中我們使用了一個已經打開的數據庫,通過datareader選擇images。接著用Response.BinaryWrite代替Response.Write來顯示image文件。

  希望您喜歡這些文章,如有任何意見和建議請致信[email protected]

本文轉載自中國軟件(http://www.csdn.Net)。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved