熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

在ASP.net 中從sqlserver檢索(retrieve)圖片

2013-11-13 11:06:51  來源: .NET編程 
  介紹

  這篇文章是我寫的如何把圖片存入sqlServer中的後續我建議你在讀這篇文章之前先看看那篇

  和存儲圖片相比讀取圖片就要簡單多了輸出一副圖片我們要做的就是使用Response對象的BinaryWrite方法同時設置圖片的格式在這篇文章中我們將討論如何從SqlServer中檢索圖片並將學習以下幾個方面的知識

  1.如何設置圖片的格式?

  2.如何使用BinaryWrite方法
 

  我們已經在Person表中存儲了數據那麼我們就寫些代碼來從表中讀取數據下面的代碼檢索了所有的值從Person表中

從sqlserver中讀取圖片的代碼

Public Sub Page_Load(sender As Object e As EventArgs)
Dim myConnection As New SqlConnection(ConfigurationSettingsAppSettings(ConnectionString))
Dim myCommand As New SqlCommand(Select * from Person myConnection)
Try
myConnectionOpen()
Dim myDataReader as SqlDataReader
myDataReader = myCommandExecuteReader(CommandBehaviorCloseConnection)

Do While (myDataReaderRead())
ResponseContentType = myDataReaderItem(PersonImageType)
ResponseBinaryWrite(myDataReaderItem(PersonImage))
Loop

myConnectionClose()
ResponseWrite(Person info successfully retrieved!)
Catch SQLexc As SqlException
ResponseWrite(Read Failed : & SQLexcToString())
End Try
End Sub

  看看他是怎麼工作的?

  上面的例子很簡單我們所作的就是執行一個sql語句再循環讀取所有的記錄(looping through all the records)在顯示圖片之前我們先設置了圖片的contentType然後我們使用BinaryWrite方法把圖片輸出到浏覽器

源代碼

/// retrivingaspx

<%@ Page Language=VB %>
<%@ Import Namespace=SystemData %>
<%@ Import Namespace=SystemDataSqlClient %>
<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(ConfigurationSettingsAppSettings(ConnectionString))
Dim myCommand As New SqlCommand(Select * from Person myConnection)
Try
myConnectionOpen()
Dim myDataReader as SqlDataReader
myDataReader = myCommandExecuteReader(CommandBehaviorCloseConnection)

Do While (myDataReaderRead())
ResponseContentType = myDataReaderItem(PersonImageType)
ResponseBinaryWrite(myDataReaderItem(PersonImage))
Loop

myConnectionClose()
ResponseWrite(Person info successfully retrieved!)
Catch SQLexc As SqlException
ResponseWrite(Read Failed : & SQLexcToString())
End Try
End Sub

</script>
</HEAD>
<body style=font: pt verdana>
</body>
</HTML>


From:http://tw.wingwit.com/Article/program/net/201311/15185.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.