Click here to Skip to main content
Licence 
First Posted 30 May 2004
Views 275,934
Bookmarked 46 times

Display Images from Database in ASP

By | 30 May 2004 | Article
This article describes how to display images which are stored in database in either SQL Server or MS Access.

Introduction

This article describes how to display images which are stored in a database. You can use <IMG> tag to display images stored in the database by calling another ASP page in SRC attribute of <IMG> tag.

For example:

<IMG SRC="ShowPicture.asp?PhotoId=1">

where PhotoId is the ID stored in the database.

Using the code

Following are the steps which needs to be executed:

  1. Create table Users in MS-Access or SQL server.
  2. Create ShowPicture.asp page.
  3. Call this page using <IMG> tag wherever required.

Create table with the following structure:

Table name: Users

  • user_id (AutoNumber)
  • user_name (Text)
  • user_photo (Ole Object - For MS-Access, and Image data type for SQL server).

Code

ShowPicture.asp is used to display images. You need to pass user ID in querystring, and for that user ID, image will be displayed. Following is the code:

 'Declare Variables..
    Dim sql
    Dim rs
    Dim conn
    Dim userID,str
    
   userID = Request("PhotoId")
   If userID = "" Then userID = 0
   
   'Instantiate Objects
   Set conn = Server.CreateObject("ADODB.Connection")
   Set rs = Server.CreateObject("ADODB.Recordset")
   
   'Open connection
   Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
             "Data Source=" & Server.MapPath("data.mdb")
   
   'Get the specific image based on the ID passed in a querystring
    str = "SELECT user_photo FROM users where user_id =" & userID
    rs.Open str, conn,3,3
    if rs.eof then 'No records found
        Response.End
    else 'Display the contents
        Response.ContentType = "image/gif" 
        Response.BinaryWrite(rs("user_photo")) 
    end if
   
   'destroy the variables.
   rs.Close
   conn.Close
   set rs = Nothing
   set conn = Nothing

Please note that "Response.contentType" will depend on the type of content you would like to display. For example, to display jpg image, following will be the code:

     Response.ContentType = "image/jpg"

To use above page for displaying images, following is the example:

     <IMG SRC="ShowPicture.asp?PhotoId=1">
     <IMG SRC="ShowPicture.asp?PhotoId=2">

Upload Image

Following example shows how to upload images in database by using ASPSmartUpload component. More information about this component can be found here.

Following is the code to upload image:

<FORM METHOD="POST" ACTION="saveFile.asp" 
        ENCTYPE="multipart/form-data" NAME="UploadForm">
   <center>
   Employee Name : <INPUT TYPE="TEXT" NAME="USERNAME" SIZE="30"><br>
   <INPUT TYPE="FILE" NAME="UPLOADFILE1" SIZE="50">
   </center>
   <BR>
   <center><INPUT TYPE="SUBMIT" VALUE="Upload" 
             id=SUBMIT1 name=SUBMIT1></center>
</FORM>

Code to save the image in the database:

Dim myupload
   'declare variables..
   intCount=0
        
    ' Create Upload Component
    Set myupload = Server.CreateObject("aspSmartUpload.SmartUpload")
    myupload.Upload

    'Create Connection
    Set Conn = Server.CreateObject("ADODB.Connection")
    Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
              "Data Source=" & Server.MapPath("data.mdb")
   
    Set Rs = Server.CreateObject("ADODB.recordset")
    Rs.Open "SELECT user_id,user_name,user_photo FROM users", Conn,3,3

    'Select each file
    For each file In myupload.Files
        If not file.IsMissing Then 'Check for missing file
            'Add the current file in database
            Rs.AddNew
            file.FileToField Rs.Fields("user_photo")
            Rs("user_name") = myupload.Form("USERNAME")
            Rs.Update
            intCount = intCount + 1
        End If
    Next
    Response.Write(intCount & " file(s) uploaded.")
    'Destroy the objects...

Comments

It is always better to store images in the file system rather than storing in the database. Only image path can be stored in the database. However, storing images in the database depends on requirements and needs.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Om Prakash Pant

Web Developer

India India

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 4 Pinmembermanoj kumar choubey6:06 21 Jan '12  
Question"Error" Invalid class string [modified] Pinmemberwahed210214:53 11 Jun '11  
GeneralI want to do this but with ASP reading from an MS Access 2007 Attachment field. PinmemberScottsr14:20 5 Apr '11  
GeneralMy vote of 5 PinmemberMember 20445290:40 12 Feb '11  
GeneralMy vote of 4 Pinmembercodemoreforless10:50 8 Aug '10  
GeneralRbmBinaryImage PinmemberRMostafa21:49 26 Apr '09  
GeneralI want to store the checkboxs and textboxs values in database - asp Pinmembershivasusan22:28 29 Oct '08  
GeneralWith Sql but asp.net - simple with asp Pinmembermayurmv17:24 5 Sep '08  
GeneralI want Code for serch data statewise from all state Pinmemberinfluxsam20:30 4 May '08  
GeneralAccess 2007/SQL Express 2005 and viewing images from ASP PinmemberJstncase9:10 16 Apr '08  
GeneralRe: Access 2007/SQL Express 2005 and viewing images from ASP PinmemberScottsr14:25 5 Apr '11  
GeneralThanks PinmemberCuchuk Sergey21:54 10 Feb '08  
GeneralHi Can you suggest how to Upload Images in ASP.NET Pinmemberkodalis5:59 29 May '07  
GeneralRe: Hi Can you suggest how to Upload Images in ASP.NET PinmemberBilal Haider Asi4:22 1 Aug '07  
AnswerRe: Hi Can you suggest how to Upload Images in ASP.NET Pinmembertfzwgd16:44 1 Dec '09  
QuestionNo duplicate files Pinmemberdlbdennis17:49 10 May '07  
Questionhow to put flash pgms PinmemberShyju.K19:42 18 Feb '07  
General.jpg images from access database displayed as garble PinmemberMember #38120463:18 9 Feb '07  
GeneralDisplay all images Pinmemberbrtakaram0:24 14 Dec '06  
GeneralRe: Display all images Pinmemberbrtakaram6:48 19 Dec '06  
GeneralDisplay image along with text Pinmembertonyg2smith6:02 18 Oct '06  
Hello all,
 
I'm stuck with a stupid error, having spent the last few hours looking for an answer and not finding one I am hoping that maybe someone here will have a solution for me!
 
Problem is, I can display an image on an .aspx page, using the following;
 
Response.BinaryWrite(row("empPhoto"))
 
When this line is included in my code, it ONLY displays the image and no the other tables, text etc that is on the page. No idea why, maybe someone else has come across this and can provide a workaround.
 
Or maybe someone can suggest a way of displaying an image from the database on a page along with text, maybe the response.binarywrite method isn't the best way of going about this.
 
I would really appreciate any help someone could provide me with for this.
 
Thanks in advance,
 
Tony
 

Dim ID As String
ID = Request.QueryString("ID")
 
Dim strConnString As String
strConnString = ConfigurationManager.ConnectionStrings("SqlConnect").ConnectionString
 
Dim myConnection As New SqlConnection(strConnString)
Dim sql As String = "SELECT * FROM Employee WHERE empID = @empID"
Dim cmd As New SqlCommand(sql, myConnection)
 
cmd.Parameters.AddWithValue("@empID", ID)
 
myConnection.Open()
 
Dim adapt As New SqlDataAdapter(cmd)
Dim table As New Data.DataTable
 
adapt.Fill(table)
 
Dim row As Data.DataRow
For Each row In table.Rows
 
Response.BinaryWrite(row("empPhoto"))
 
Dim empID As String = (row("empID"))
lblID.Text = empID
Dim empName As String = (row("empName"))
lblName.Text = empName
lblName.Visible = True
Dim empPhoto As Byte()
empPhoto = (row("empPhoto"))
imgPhoto.EnableViewState = True
Next
 
myConnection.Close()
GeneralRe: Display image along with text Pinmemberrameshkumarp3:15 20 Feb '07  
AnswerRe: Display image along with text Pinmembertonyg2smith3:42 23 Feb '07  
QuestionUnable to Upload Image with aspSmartUpload component [modified] Pinmemberasprajesh0:13 16 Oct '06  
Questionsmartupload component ? Pinmembercoolraazi0:04 11 Oct '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 31 May 2004
Article Copyright 2004 by Om Prakash Pant
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid