help,how to display a photo which have got from DB BLOB in jsp

Discussions

Web tier: servlets, JSP, Web frameworks: help,how to display a photo which have got from DB BLOB in jsp

  1. hello all

    help me
    how to display a photo which have been got from database BLOB field in jsp?

    tanks and regards
  2. Do the following.

    1. Use the html:image tag
    <html:image src="DisplayImageServlet?imageId=n"/>

    Where n is the id for the image in the DB

    2. Write DisplayImageServlet on the lines of

            byte[] image = persistence.loadImage(n);
            response.reset();
            response.setContentType("image/jpeg");
            out.write(image);

    3. Now about converting BLOB into byte array.
       You could do this using the getBytes method in java.sql.Blob interface. However, this may not work for Oracle 9i as getBytes returns the Oracle blob locator. For this case there is an excellent blog which worked for me.

    http://hansonchar.blogspot.com/2005/06/oracle-blob-mapped-to-byte-in.html
     
    Regards,
    Ashish Jamthe
    TRL, Telstra
  3. if you want best approach[ Go to top ]

    Generate the dynamic URL for your image to hit the same server and send the response. When it is trying to display the image, once again a new request will hit your server. At that time just stream the image by using response PrintWriter.
  4. This code looks nice, but you may want to avoid loading the entire image in memory ( byte[] image = persistence.loadImage(n); ). If you have many simultaneous connections this will end up allocating a lot of unnecessary (potentially big) memory and your webapp's memory footprint will increase in an unpredictable way, which will end up giving more work to the garbage collector and reduce the number of active sessions you can keep in memory.

    Instead of loading the entire image each time, you may want to consider a streaming approach. The JDBC api lets you stream data from blobs. You can you use this feature to transfer your binary content in small chunks, ideally using statically allocated buffers.

    Regards,
    Emil Kirschner ( http://www.thekirschners.com/ )