在Asp.Net中從sqlserver檢索(retrieve)圖片
發(fā)表時間:2023-08-17 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]出處:www.ASPAlliance.com介紹:這篇文章是我寫的"如何把圖片存入sqlServer中"的后續(xù)。我建議你在讀這篇文章之前先看看那篇。和存儲圖片相比,讀取圖片就要簡...
出處:www.ASPAlliance.com
介紹:
這篇文章是我寫的"如何把圖片存入sqlServer中"的后續(xù)。我建議你在讀這篇文章之前先看看那篇。
和存儲圖片相比,讀取圖片就要簡單多了。輸出一副圖片我們要做的就是使用Response對象的BinaryWrite方法。
同時設(shè)置圖片的格式。在這篇文章中,我們將討論如何從SqlServer中檢索圖片。
并將學(xué)習(xí)以下幾個方面的知識.
·如何設(shè)置圖片的格式?
·如何使用BinaryWrite方法。
我們已經(jīng)在Person表中存儲了數(shù)據(jù),那么我們就寫些代碼來從表中讀取數(shù)據(jù)。
下面的代碼檢索了所有的值從Person表中。
從sqlserver中讀取圖片的代碼.
Public Sub Page_Load(sender As Object, e As EventArgs)
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("Select * from Person", myConnection)
Try
myConnection.Open()
Dim myDataReader as SqlDataReader
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
Do While (myDataReader.Read())
Response.ContentType = myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop
myConnection.Close()
Response.Write("Person info successfully retrieved!")
Catch SQLexc As SqlException
Response.Write("Read Failed : " & SQLexc.ToString())
End Try
End Sub
看看他是怎么工作的?
上面的例子很簡單。我們所作的就是執(zhí)行一個sql語句,再循環(huán)讀取所有的記錄(looping through all the records).
在顯示圖片之前,我們先設(shè)置了圖片的contentType,然后我們使用BinaryWrite方法把圖片輸出到瀏覽器。
源代碼:
/// retriving.aspx
<%@ Page Language="vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<HTML>
<HEAD>
<title>Retrieving Image from the Sql Server</title>
<script runat=server>
Public Sub Page_Load(sender As Object, e As EventArgs)
' Create Instance of Connection and Command Object
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("Select * from Person", myConnection)
Try
myConnection.Open()
Dim myDataReader as SqlDataReader
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
Do While (myDataReader.Read())
Response.ContentType = myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop
myConnection.Close()
Response.Write("Person info successfully retrieved!")
Catch SQLexc As SqlException
Response.Write("Read Failed : " & SQLexc.ToString())
End Try
End Sub
</script>
</HEAD>
<body style="font: 10pt verdana">
</body>
</HTML>