How to Display Images in JSP retrieved from database using blob

Discussions

Web tier: servlets, JSP, Web frameworks: How to Display Images in JSP retrieved from database using blob

  1. hi

    i want to display the image stored in the database, i am storing as blob, i am able to retrieve the image and i want to display it in the jsp page , can u just give either the code or sample how to do it.

    thanks in advance
    srini
  2. Hello Srini.

    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).

    <%@ 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;

    %>

    This is only a test page, of course you should use some kind of connection pooling etc. in production sites.

    Stefan