在ASP.NET中從SQL Server檢索圖片
和存儲圖片相比,讀取圖片就要簡單多了。輸出一副圖片我們要做的就是使用Response對象的BinaryWrite方法。
同時設置圖片的格式。在這篇文章中,我們將討論如何從SqlServer中檢索圖片。並將學習以下幾個方麵的知識。
·如何設置圖片的格式?
·如何使用BinaryWrite方法。
我們已經在Person表中存儲了數據,那麼我們就寫些代碼來從表中讀取數據。
下麵的代碼檢索了所有的值從Person表中。
從sqlserver中讀取圖片的代碼。
PublicSubPage_Load(senderAsObject,eAsEventArgs)
DimmyConnectionAsNewSqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
DimmyCommandAsNewSqlCommand("Select*fromPerson",myConnection)
Try
myConnection.Open()
DimmyDataReaderasSqlDataReader
myDataReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection)
DoWhile(myDataReader.Read())
Response.ContentType=myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop
myConnection.Close()
Response.Write("Personinfosuccessfullyretrieved!")
CatchSQLexcAsSqlException
Response.Write("ReadFailed:"&SQLexc.ToString())
EndTry
EndSub
看看他是怎麼工作的?
上麵的例子很簡單。我們所作的就是執行一個sql語句,再循環讀取所有的記錄(loopingthroughalltherecords).
在顯示圖片之前,我們先設置了圖片的contentType,然後我們使用BinaryWrite方法把圖片輸出到瀏覽器。
源代碼:
///retriving.aspx
<%@PageLanguage="vb"%>
<%@ImportNamespace="System.Data"%>
<%@ImportNamespace="System.Data.SqlClient"%>
<HTML>
<HEAD>
<title>RetrievingImagefromtheSqlServer</title>
<scriptrunat=server>
PublicSubPage_Load(senderAsObject,eAsEventArgs)
'CreateInstanceofConnectionandCommandObject
DimmyConnectionAsNewSqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
DimmyCommandAsNewSqlCommand("Select*fromPerson",myConnection)
Try
myConnection.Open()
DimmyDataReaderasSqlDataReader
myDataReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection)
DoWhile(myDataReader.Read())
Response.ContentType=myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop
myConnection.Close()
Response.Write("Personinfosuccessfullyretrieved!")
CatchSQLexcAsSqlException
Response.Write("ReadFailed:"&SQLexc.ToString())
EndTry
EndSub
</script>
</HEAD>
<body>
</body>
</HTML>
最後更新:2017-04-02 00:06:35