2

I'm trying to create a small servlet that uploads images and is able to retrieve them in a different page as a slideshow.

I'm able to save them outside the WebApp folder, but while retrieving them I need them to be a part of a JSP which will have other content, apart from the images. Currently, I'm using BufferedImage and ImageIO classes to stream the images one at a time.

BufferedImage image = ImageIO.read(new File("D:\\"+file.getName())); ImageIO.write(image, "jpg", response.getOutputStream()); 

The file is checked to be a JPEG file type earlier in the code.

2
  • You shouldn't use ImageIO: you're reading bytes representing a JPG-encoded image, then transforming the stream of bytes into a BufferedImage, then transforming this buffered image into bytes representing a JPG-encoded image. Just read the bytes and send them as is to the response output stream. Commented Jun 13, 2012 at 10:59
  • Yeah I've tried that as well by simple reading them using BufferedInputStream and then writing it using BufferedOutputStream. That gives me the same end result. What I want to have is a list of images and not a single image. Commented Jun 13, 2012 at 11:16

2 Answers 2

1

You need to understand how HTTP and HTML work:

  1. The browser asks for an HTML page (first request)
  2. The server sends back HTML (and HTML only), containing 3 <img src="..."/> tags
  3. The browser sends a request to get the bytes of the first image (second request)
  4. The server sends back the bytes of the first image
  5. The browser sends a request to get the bytes of the second image (third request)
  6. The server sends back the bytes of the second image
  7. The browser sends a request to get the bytes of the third image (fourth request)
  8. The server sends back the bytes of the third image

So, you need a servlet or JSP which generates the HTML page, containing all your <img src="..."/> tags. Each of this tag should have the following form:

<img src="imageServlet?imageId=564"/> 

And you need a second servlet, mapped to imageServlet, which reads the bytes of the image identified by the imageId parameter value from the file system, and write those bytes to the response output stream.

Sign up to request clarification or add additional context in comments.

Comments

1

them I need them to be a part of a JSP which will have other content,

Use image tag in JSP

<image src="/context-root/YourServlet?param=value" alt="blah blah"/> 

1 Comment

I need to have multiple such image tags. How do I generate them at runtime?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.