Displaying Images saved in Database of blob datatype in JSP

Share this Article :


Most of the times,  we need to display images  from Database,  This Article will guide you  to display  images  saved in  database

When we are saving  images to the database,  its a better  option  to save  the image type also,  it will be  helpful  when we are retreiving  image from database,  it is  fine when we are handling or saving  only one type of  image format  i.e either  jpg or GIF  but  what if  we  are allowing users to upload  both  jpg, gif  or any other  image format.  So,   Better to have a another field  to save  the image type also by which  we can  straight away throw  the  required headers  to the page .. i.e

response.setContentType(“image/jpeg”);
or

response.setContentType(“image/gif”);


Take a look at the following JSP Page. Important ist the setting of the ContentType for the response header, i.e. to “image/gif” or “image/jpeg” (in this case a database field, too).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
 
Class.forName("com.inet.tds.TdsDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:inetdae7:encharmion_nt4?database=RS", "Vignette", "vignette");
 
String strSQL = "SELECT ContentType, ImageBinary "
+ "FROM Images "
+ "WHERE (ImageID=" + request.getParameter("imageid") + ")";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(strSQL);
rs.next();
 
response.setHeader("expires", "0");
response.setContentType(rs.getString("ContentType"));
 
out.clear();
OutputStream os = response.getOutputStream();
os.write(rs.getBytes("ImageBinary"));
out.flush();
return;
 
%>

Written by bhaskar

{bhaskar has written 11 posts on ITTreats.com . See all posts by }


Leave a Reply