在Asp.Net 中從sqlserver檢索(retrieve)圖片 (轉)

worldblog發表於2007-12-12
在Asp.Net 中從sqlserver檢索(retrieve)圖片 (轉)[@more@]

在 中從server檢索(retrieve)圖片

出處:

介紹:
這篇文章是我寫的"如何把圖片存入sqlServer中"的後續。我建議你在讀這篇文章之前先看看那篇。
和圖片相比,讀取圖片就要簡單多了。輸出一副圖片我們要做的就是使用Response的BinaryWrite方法。
同時設定圖片的格式。在這篇文章中,我們將討論如何從SqlServer中檢索圖片。
並將學習以下幾個方面的知識.
·如何設定圖片的格式?
·如何使用BinaryWrite方法。

我們已經在Person表中儲存了資料,那麼我們就寫些程式碼來從表中讀取資料。
下面的程式碼檢索了所有的值從Person表中。

從sqlserver中讀取圖片的程式碼.
 Public Sub Page_Load(sender As , e As EventArgs)
  Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
  Dim myCommand As New SqlCommand(" * from Person", myConnection)
  Try
  myConnection.Open()
  Dim myDataReader as SqlDataReader
  myDataReader = myCommand.ExecuteReader(Commanehavior.CloseConnection)

  Do While (myDataReader.Read())
  Response.ContentType = myDataReader.Item("PersonImageType")
  Response.BinaryWrite(myDataReader.Item("PersonImage"))
  L

  myConnection.Close()
  Response.Write("Person info succesully retrieved!")
  Catch SQLexc As SqlException
  Response.Write("Read Failed : " & SQLexc.ToString())
  End Try
  End Sub

看看他是怎麼工作的?
上面的例子很簡單。我們所作的就是一個sql語句,再迴圈讀取所有的記錄(loo through all the records).
在顯示圖片之前,我們先設定了圖片的contentType,然後我們使用BinaryWrite方法把圖片輸出到。


/// retriving.





 


  Retrieving Image from the
 
<BR>&nbsp; Public Sub Page_Load(sender As Object, e As EventArgs)<BR>&nbsp; ' Create Instance of Connection and Command Object<BR>&nbsp; Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))<BR>&nbsp; Dim myCommand As New SqlCommand("Select * from Person", myConnection)<BR>&nbsp; Try<BR>&nbsp; myConnection.Open()<BR>&nbsp; Dim myDataReader as SqlDataReader <BR>&nbsp; myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)<BR>&nbsp; </P> <P>&nbsp; Do While (myDataReader.Read())<BR>&nbsp; Response.ContentType = myDataReader.Item("PersonImageType")<BR>&nbsp; Response.BinaryWrite(myDataReader.Item("PersonImage"))<BR>&nbsp; Loop&nbsp; </P> <P>&nbsp; myConnection.Close()<BR>&nbsp; Response.Write("Person info successfully retrieved!")<BR>&nbsp; Catch SQLexc As SqlException<BR>&nbsp; Response.Write("Read Failed : " & SQLexc.ToString())<BR>&nbsp; End Try<BR>&nbsp; End Sub&nbsp; </P> <P>&nbsp;

 
 
 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-991639/,如需轉載,請註明出處,否則將追究法律責任。

相關文章