|
Written on: May, 15th 2002. |
Introduction
This article is a continuation of my previous article, which talks about Inserting an image to Sql Server. I would recommend to read the above article before continuing this.
Compared to inserting an image, retreiving is very simple. The only new thing that we need to write an image is, we need to use the method BinaryWrite of the Response Object. Also we need to set the appropriate content type. In this article, we will discuss about retrieving images from a Sql Server.
We will be learning the following aspects in this article.
- How to set the Content Type?
- How to use the method, BinaryWrite
Since we already have data in the table, Person, we will add some statements which retrieves all the rows from the table, person. The following code retrieves all rows from the table, Person.
Code to retrieve image from sql server.
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 |
How it works?
The above example is very very simple. All we are doing is executing a sql statement and looping through all the records. We are displaying only the Image from the table, Person. Before dispalying the image, we first set the contentType. Then we write the image to' the browser using the method, BinaryWrite
Test this Script
Download the code
Click here to download the ASPX page
Conclusion
Thus we saw how to retrieve images from a sql server. Do not forget to read my article which talks about inserting images to a sql server.
Links
Inserting Image to SqlServer
Retrieving Images from SqlServer and displaying in a DataGrid
How to Upload a File?
Textbox Web Server Control
Send your comments to das@aspalliance.com