Results 1 to 10 of 10
Like Tree1Likes
  • 1 Post By Tolls

Thread: display image from database on jsp page

  1. #1
    rdangelo is offline Member
    Join Date
    Jun 2012
    Posts
    5
    Rep Power
    0

    Default display image from database on jsp page

    Hello there, this is my first post on this forum (please let me know if this is the wrong place for this post).
    I am writing about how to display an image stored in a postgresql database as a bytea type, on a java/jsp webpage. I am developing on Linux Karmic Koala, using Eclipse editor with Tomcat plugin, Tomcat 5.5 and Firefox browser. So far I've tried three methods, one using a servlet, one running the main method on the Eclipse command console, and the other calling a regular java class method from a jsp page. So far all three have been unsuccessful.

    The application I'm developing for my company is just a dating website, the application name is "lovestory" and it's located on "/home/ricardo/workspace/lovestory/" on my laptop, and I'm developing with java/jsp.

    Here's what I've done so far:

    1. Servlet method
    Java Code:
    	public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	String img = null;
    	try {
    		String query = "select img from profile_m where shimei='image1'";
    		Statement stm = con.createStatement();
    		ResultSet rs = stm.executeQuery(query);
    		rs.next();
    		img = rs.getString("img");
    		byte[] img2 = new byte[img.length()];
    		InputStream imgstream = rs.getBinaryStream("img");
    		int index = imgstream.read(img2, 0, img.length());
    		stm.close();
    		res.reset();
    		res.setContentType("image/jpg");
    		res.getOutputStream().write(img2,0,img2.length);
    		res.getOutputStream().flush();
    		imgstream.close();
    	}
    	catch (SQLException e) { e.printStackTrace(); }
    	catch (Exception e) { e.printStackTrace(); }
    	}
    When I call the above servlet (called GetImg) from Firefox, I get a blank page with the text "http://localhost:8080/lovestory/GetImg" written on top, which is exactly what I entered on the browser to call the servlet, and no error messages. By the way, the text does not behave like text, I cannot highlight it, behaves more like an image!

    2. main method
    Java Code:
    	public static void main(String[] args) {
    		try {
    			String query = "select img from profile_m where shimei='image1'";
    			Statement stm = con.createStatement();
    			ResultSet rs = stm.executeQuery(query);
    			rs.next();
    			byte[] imgbytes = rs.getBytes("img");
    			File file = new File("/home/ricardo/Desktop/testimage.jpg");
    			OutputStream toFile = new FileOutputStream(file);
    			toFile.write(imgbytes);
    			rs.close();
    			stm.close();
    			imgstream.close();
    			toFile.close();
    		}
    		catch (IOException e) { e.printStackTrace(); }
    		catch (SQLException e) { e.printStackTrace(); }
    	}
    When I run main on the Eclipse command console, I also get no error messages, but the image file that was created does not display either on my image viewer program which says the file is actually not a jpeg file, nor on Firefox browser which actually displays a blank page with the file path "file:///home/ricardo/Desktop/testimage.jpg" displayed on top (again behaving like an image instead of text).

    3. getPicture() method
    Java Code:
    	public static byte[] getPicture() {
    		byte[] imgbytes = null;
    		try {
    			String query = "select img from profile_m where shimei='image1'";
    			Statement stm = con.createStatement();
    			ResultSet rs = stm.executeQuery(query);
    			rs.next();
    			imgbytes = rs.getBytes("img");
    			rs.close();
    			stm.close();
    		}
    		catch (SQLException e) { e.printStackTrace(); }
    		catch (Exception e) { e.printStackTrace(); }
    		return imgbytes;
    	}
    section of webpage (http://localhost:8080/lovestory/henkou1.jsp) where I call image:
    Java Code:
    	<%
    	try {
    		byte[] img = Db_transactions.getPicture();
    		response.setContentType("image/jpg");
    		response.setContentLength(img.length);
    		response.getOutputStream().write(img);
    		response.getOutputStream().flush();
    		response.getOutputStream().close();	
    	}
    	catch (IOException e) { e.printStackTrace(); }
    	catch (NullPointerException e) { e.printStackTrace(); }
    	catch (Exception e) { e.printStackTrace(); }
    	%>
    Finally, when I call getPicture() from henkou1.jsp, I get about the same result as the above two methods: the text "http://localhost:8080/lovestory/henkou1.jsp" which is what I entered on the browser, written on top of a blank page and behaving like an image again. This time I also get the following error message: "java.lang.IllegalStateException: getOutputStream() has already been called for this response"

    This is my first experience trying to display images from a database in raw byte format, any help will be much appreciated.
    Last edited by rdangelo; 06-22-2012 at 06:55 AM.

  2. #2
    Tha Boss is offline Member
    Join Date
    Jun 2012
    Location
    ON, Canada.
    Posts
    25
    Rep Power
    0

    Default Re: display image from database on jsp page

    I will suggest you store the pictures your program is calling in a folder that's within the program package. By doing this, not only will the pictures go wherever your program goes but it will be much easier to make use of the System.getProperty() method. Like so:

    String userDir = System.getProperty("user.dir");

    Doing so you automatically pinpoint the directory the program is being run from. I would then trace the directory like so:

    System.out.println(userDir);

    Run the program, and in the directory it outputs, create a folder in which you will store all the pictures or whatever, and put them in there.
    Your program can now locate that image and store in a variable like so:

    ImageIcon picture = new ImageIcon(userDir + "\\pictures\\pic.jpg");

    Now whenever you output that variable you should see the image it's pointed at.
    Hope this helps...
    - CHEERS!

    E.Hughes
    "I'm sometimes hard to please... because I'm only satisfied with the very best." - Fernand Point.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: display image from database on jsp page

    That is not much use for someone doing a webapp.
    The way the OP is handling images (as resources in a database) is prefectly correct for things like user profiles.

    For the OP, first off on the servlet method. Start with the criticism, looks like your connection 'con' is an attribute on your servlet. Don't do this. Servlets should not have attributes as they are not threadsafe (two users accessing the servlet at the same time will use the same connection object and thus interfere with each others transactions).

    That aside, you seem to be trying to get the img as a String and as a stream. Don't do this. Just get the stream and read from the stream, writing a byte[] buffer of some size each time (say 8k, that's about what I use).
    Java Code:
    byte[] buffer = new byte[8192];
    int byteCount = 0;
    while((byteCount = imgstream.read(buffer)) > -1) {
       outputStream.write(buffer, byteCount);
    }
    // Flush.
    As for the other ones, I've never used getBytes, but I suspect that's where you problem lies. IMO you should read and write in chunks, which will reduce the footprint of your app massively. In the code above it doesn't matter how big the image is, we only use 8k to transfer it.
    Fubarable likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    Tha Boss is offline Member
    Join Date
    Jun 2012
    Location
    ON, Canada.
    Posts
    25
    Rep Power
    0

    Default Re: display image from database on jsp page

    Oops, this one's for a webapp, my bad... think I posted that on the wrong thread. Oh well.

    E.Hughes
    "I'm sometimes hard to please... because I'm only satisfied with the very best." - Fernand Point.

  5. #5
    rdangelo is offline Member
    Join Date
    Jun 2012
    Posts
    5
    Rep Power
    0

    Default Re: display image from database on jsp page

    Thanks for the responses guys! unfortunately the problem still persists. One thing I should have included in my first post is HOW I insert the images in postgresql in the first place (I will below)
    (for Toll) I carefully studied your example code and modified my servlet to look like this (the entire servlet):
    Java Code:
    package core;
    import java.io.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    public class GetImg extends HttpServlet {	
    	public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	String img = null;
    	Connection con = null;
    	try {
    		con = Db_transactions.getCon();
    		String query = "select img from profile_m where shimei='lennon'";
    		Statement stm = con.createStatement();
    		ResultSet rs = stm.executeQuery(query);
    		rs.next();
    		InputStream imgstream = rs.getBinaryStream("img");
    		byte[] img2 = new byte[8192];
    		int index = 0;
    		res.setContentType("image/jpg");
    		while ((index = imgstream.read(img2)) > -1) {
    			res.getOutputStream().write(img2);
    		}
    		res.getOutputStream().flush();
    		res.getOutputStream().close();
    		imgstream.close();
    		stm.close();
    	}
    	catch (SQLException e) { e.printStackTrace(); }
    	catch (Exception e) { e.printStackTrace(); }
    	return;
    	}
    }
    Now, the code that inserts the image file into the database is this:
    Java Code:
    public static profilebean doProfile(profilebean prof) {
    File imgfile = null;
    String query = null;
    InputStream fis = null;
    try {
    	query = "insert into profile_m(img,imgpath) values(?,?)";
    	PreparedStatement pstm = con.prepareStatement(query);
    	imgfile = new File(prof.getPic());
    	fis = new FileInputStream(imgfile);
    	pstm.setBinaryStream(1, fis, Integer.parseInt(String.valueOf(imgfile.length())));
    	pstm.setString(2, String.valueOf(imgfile));
    	pstm.executeUpdate();
    	pstm.close();
    	fis.close();
    	}
    	catch (FileNotFoundException e) { e.printStackTrace();  return prof; }
    	catch (IOException e) { e.printStackTrace(); return prof; }
    	catch (SQLException e) { e.printStackTrace(); return prof; }
    	catch (Exception e) { e.printStackTrace(); return prof; }
    	return prof;
    }
    And finally, this is what I get when I call the servlet from my JSP page (the same result as the other times):
    display image from database on jsp page-screenshot-1.jpg
    Again the text behaves like an image (I cannot highlight it).

    The image is supposed to look something like this:
    display image from database on jsp page-pict0007.jpg
    Again any help would be much appreciated

    By the way, what you wrote about threads (which I'm actually new to!) sounds pretty important, I actually had another question related to that, I think I'm going to make a new thread with that question

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: display image from database on jsp page

    Java Code:
    res.getOutputStream().write(img2);
    there is no guarantee that the read will read in all 8k of your byte[], so you need to tell it how much to write, which is the 'index' value.

    I wouldn't keep requesting the outputstream either, but that's stylistic more than anything else.

    Are you sure that image is in the database, and are you sure the servlet is being accessed?
    There's no logging in your code, so there's no way you can be sure this is even being executed.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    rdangelo is offline Member
    Join Date
    Jun 2012
    Posts
    5
    Rep Power
    0

    Default Re: display image from database on jsp page

    Hi, Thanks again
    Well, after messing with it for a couple more hours I decided give up on postgresql's bytea type (it was actually returning a byte count twice as large as the original file size). I'm just going to store the images in a folder and create a random number as file name. I still need to look into reading and writing an image in chunks, as you said it has benefits. For now I'll just read the whole image at once. Anyways, here's the final version (as of now):

    Read image, create random name, store in folder inside server:
    Java Code:
    String fs = System.getProperty("file.separator");
    String image = System.getProperty("user.dir") + fs + prof.getPicture();
    imgfile = new File(image);
    fis0 = new FileInputStream(imgfile);
    int x=0;
    while(fis0.read() > -1) x++;    //count number of bytes in image file
    fis0.close();
    fis = new FileInputStream(imgfile);
    byte[] bytearray = new byte[x+1];
    while(fis.read(bytearray) > -1) { };      //read image bytes from input stream object into bytearray
    imgcode = String.valueOf(System.currentTimeMillis()) + ".jpg";         //create random name
    String dbfile = System.getProperty("user.home") + fs + "Desktop" + fs + imgcode;
    imgfile = new File(dbfile);
    OutputStream fos = new FileOutputStream(imgfile);
    fos.write(bytearray);      //write image bytes from bytearray to output stream object
    fos.close();
    read image from folder and display on browser (updated version of earlier servlet):
    Java Code:
    String fs = System.getProperty("file.separator");
    String dbfile = System.getProperty("user.home") + fs + "Desktop" + fs + imgcode;
    File file0 = new File(dbfile);
    InputStream imgstream = new FileInputStream(file0);
    int x=0;
    while(imgstream.read() > -1) x++;
    imgstream.close();
    InputStream imgstream2 = new FileInputStream(file0);
    byte[] bytearray = new byte[x+1];
    while(imgstream2.read(bytearray) > -1) {};      //read image bytes from input stream object into bytearray
    res.setContentType("image/jpg");
    res.getOutputStream().write(bytearray);     //write image from bytearrray to output stream object (browser)
    res.getOutputStream().flush();
    res.getOutputStream().close();
    imgstream2.close();
    stm.close();

  8. #8
    veerarider is offline Member
    Join Date
    Sep 2012
    Posts
    1
    Rep Power
    0

    Default Re: display image from database on jsp page

    Hello ...
    Can you say ,how to store login page values in access database...with jsp coding..please anyone help me

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: display image from database on jsp page

    Please start your own thread rather than hijacking someone else's.

    Also, this is not a code factory.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,240
    Rep Power
    19

    Default Re: display image from database on jsp page

    THREAD CLOSED

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. JSP page display
    By cnu.nandhikonda@gmail.com in forum JavaServer Pages (JSP) and JSTL
    Replies: 3
    Last Post: 02-01-2012, 10:48 AM
  2. Replies: 29
    Last Post: 01-07-2012, 04:05 PM
  3. Display image on jsp page
    By shuchi.vishnoi in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 11-30-2010, 12:46 PM
  4. how to display image in jsp page(Struts)
    By rama6262 in forum Advanced Java
    Replies: 1
    Last Post: 12-21-2007, 07:50 AM
  5. How to display a database-image in a page?
    By simon in forum New To Java
    Replies: 1
    Last Post: 07-23-2007, 11:56 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •