5,530,111 members and growing! (15,963 online)
Email Password   helpLost your password?
Web Development » ASP » Howto     Intermediate

Display Images from Database in ASP

By Om Prakash P

This article describes how to display images which are stored in database in either SQL Server or MS Access.
NT4, Win2K, Win2003, Windows, ASP, Visual Studio, Dev

Posted: 30 May 2004
Updated: 30 May 2004
Views: 149,394
Bookmarked: 30 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
34 votes for this Article.
Popularity: 6.65 Rating: 4.34 out of 5
0 votes, 0.0%
1
1 vote, 2.9%
2
5 votes, 14.7%
3
8 votes, 23.5%
4
20 votes, 58.8%
5

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 P



Occupation: Web Developer
Location: India India

Other popular ASP articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 41 (Total in Forum: 41) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralWith Sql but asp.net - simple with aspmembermayurmv18:24 5 Sep '08  
GeneralI want Code for serch data statewise from all statememberinfluxsam21:30 4 May '08  
GeneralAccess 2007/SQL Express 2005 and viewing images from ASPmemberJstncase10:10 16 Apr '08  
GeneralThanksmemberCuchuk Sergey22:54 10 Feb '08  
GeneralHi Can you suggest how to Upload Images in ASP.NETmemberkodalis6:59 29 May '07  
GeneralRe: Hi Can you suggest how to Upload Images in ASP.NETmemberBilal Haider Asi5:22 1 Aug '07  
QuestionNo duplicate filesmemberdlbdennis18:49 10 May '07  
Generalhow to put flash pgmsmemberShyju.K20:42 18 Feb '07  
General.jpg images from access database displayed as garblemember4:18 9 Feb '07  
GeneralDisplay all imagesmemberbrtakaram1:24 14 Dec '06  
GeneralRe: Display all imagesmemberbrtakaram7:48 19 Dec '06  
GeneralDisplay image along with textmembertonyg2smith7:02 18 Oct '06  
GeneralRe: Display image along with textmemberrameshkumarp4:15 20 Feb '07  
AnswerRe: Display image along with textmembertonyg2smith4:42 23 Feb '07  
QuestionUnable to Upload Image with aspSmartUpload component [modified]memberasprajesh1:13 16 Oct '06  
Questionsmartupload component ?membercoolraazi1:04 11 Oct '06  
Generalimage pathmemberM1K3Y2:00 5 Jun '06  
Questionhow to download a file from database in asp?memberpusycat2:04 18 May '06  
GeneralNot Uploading to SQL Databasememberin4_mus10:22 19 Mar '06  
GeneralDisplay Images from Database in ASP when we activate sample.asp x box will appear instead of our picture 1 ,2 which was written by Om Prakash Pmemberalsadig5:02 19 Dec '05  
Generalwhen we activate sample.asp x box will appear instead of our picture 1 ,2memberalsadig4:55 19 Dec '05  
Generalsample.aspmemberalsadig4:52 19 Dec '05  
GeneralHow to update the images files from database?memberRSRT13:27 26 May '05  
GeneralRe: How to update the images files from database?memberOm Prakash P0:06 27 Jun '05  
GeneralRe: How to update the images files from database?memberbasg22:44 12 May '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 30 May 2004
Editor: Smitha Vijayan
Copyright 2004 by Om Prakash P
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project