How To Display an Image on a Web Page When the Path Is Stored in a Database (299320)



The information in this article applies to:

  • ActiveX Data Objects (ADO) 2.1
  • ActiveX Data Objects (ADO) 2.1 SP1
  • ActiveX Data Objects (ADO) 2.1 SP2
  • ActiveX Data Objects (ADO) 2.5
  • ActiveX Data Objects (ADO) 2.6

This article was previously published under Q299320

SUMMARY

It is not always practical to store images that are needed in a Web site in a database; it may be more practical to store a path to the image. Even though the path is stored, you can still use that image in an Active Server Pages (ASP) page. This article illustrates how to show images when just the path is stored in the database.

MORE INFORMATION

Step-by-Step Example

  1. In Microsoft SQL Server, open the PUBS sample database, and create a new table named ImgTable.
  2. Create the following fields in ImgTable:

    Name     DataType     Size
    imgID     Char         10
    imgPath   Char         30
    						

  3. Add a record to the database with the following values: an imgID with a value of 1, and an imgPath with a value that is the full path of a .gif or .bmp file on your Microsoft Internet Information Server (IIS) computer. You will most likely find a .bmp file in the Windows or WINNT folder. The value in the imgPath column should look similar to the following:

    C:\Windows\circles.bmp
    						

  4. In Notepad, create a new ASP page named ImagePath.asp, and paste the following code:

    Note You must change User ID=<UID> and password=<strong password> to the correct values before you run this code. Make sure that <UID> has the appropriate permissions to perform this operation on the database.
    <%@ language="vbscript" %>
    <HTML>
    <BODY>
    <%
    dim cn
    dim rs
    
    set cn=server.createobject("ADODB.Connection")
    set rs=server.createobject("ADODB.Recordset")
    
    cn.open "Provider=SQLOLEDB;data source=servername;" & _
    "initial catalog=pubs;user id=<UID>;password=<strong password>"
    set rs.activeconnection = cn
    
    rs.source = "select imgPath from ImgTable where imgID=1"
    rs.open
    %>
    <img src=<%= trim(rs.fields(0))%>>
    <%
    rs.close
    set rs=nothing
    cn.close
    set cn = nothing
    %>
    </BODY>
    </HTML>
    					
  5. Modify the connection string so that it points to the correct server and uses the correct user name and password.
  6. Save ImagePath.asp in your InetPub\Wwwroot folder on the IIS server.
  7. In your Web browser, open the page. Notice that the image appears on the page.

Modification Type:MinorLast Reviewed:7/1/2004
Keywords:kbgraphic kbhowto KB299320