在ASP.NET中從SQL Server檢索圖片
2024-07-10 12:55:28
供稿:網友
和存儲圖片相比,讀取圖片就要簡單多了。輸出一副圖片我們要做的就是使用response對象的binarywrite方法。
同時設置圖片的格式。在這篇文章中,我們將討論如何從sqlserver中檢索圖片。并將學習以下幾個方面的知識。
·如何設置圖片的格式?
·如何使用binarywrite方法。
我們已經在person表中存儲了數據,那么我們就寫些代碼來從表中讀取數據。
下面的代碼檢索了所有的值從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
看看他是怎么工作的?
上面的例子很簡單。我們所作的就是執行一個sql語句,再循環讀取所有的記錄(looping through all the records).
在顯示圖片之前,我們先設置了圖片的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 >
</body>
</html>