One of my recent assignments was to build a web page that needed to show images that are stored in a database.
CREATE TABLE PHOTOS ( IMAGEID NUMBER(10), IMAGE BLOB ) / |
CREATE OR REPLACE PROCEDURE Display_Image(p_id NUMBER) IS -- Get the blob image owa_util.mime_header('images/gif'); END; |
The web page could be called with the following URL and did what I was asked to do
img src="http://machine:port/pls/myapp/display_image?p_id=12" width="115" border="0" |
This works like a charm but has a caveat that I discovered when presenting it to the network department. The network department didn’t like the idea of exposing the database server to the Internet, which indeed is considerably unsafe.
Back to the whiteboard, I thought of using Web Service. This approach just didn’t feel right and appeared to be too complex for this little solution to build. Eventually I decided to write a JavaServer Page to do the job.
The Java class to stream the image from the database column
package image; import java.sql.*; public class images String req = "" ; } |
The JavaServer Page includes the bean so its methods can be accessed in the JSP page using scriplets and “photo” as a named bean reference
<%@ page import = "image.*" %> <%@ page import = "java.io.*" %> <%@ page import = "oracle.jdbc.OracleConnection" %> <jsp:useBean id="photo" class="image.images" scope="session" /> <% int iNumPhoto ; oracle.jdbc.driver.OracleConnection conn = null; if ( request.getParameter("imgID") != null ) { iNumPhoto = Integer.parseInt(request.getParameter("imgID")) ; try { conn = …………; conn.setAutoCommit (false); // get the image from the database byte[] imgData = photo.getPhoto( conn, iNumPhoto ) ; // display the image response.setContentType("image/gif"); OutputStream o = response.getOutputStream(); o.write(imgData); o.flush(); o.close(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { … Close the connexion … ; } } %> |
To display the image on the web, I now use the following image URL
img src="image.jsp?imgID=12" width="115" border="0" |