Example to display image using Servlet

Learn Servlet Tutorial - java servlet tutorial, Servlet API, servlet Interface, Generic servlet, advantage of servlet, what is servlet

Example to display image using Servlet

Example to display image using Servlet

In this example, we are using FileInputStream class to read image and ServletOutputStream class for writing this image content as a response. To make the performance faster, we have used BufferedInputStream and BufferedOutputStream class.

You need to use the content type image/jpeg.

In this example, we are assuming that you have java.jpg image inside the c:\test directory. You may change the location accordingly.

To create this application, we have created three files:

  1. index.html
  2. DisplayImage.java
  3. web.xml


This file creates a link that invokes the servlet. The url-pattern of the servlet is servlet1.

  1. <a href="servlet1">click for photo</a>  


This servlet class reads the image from the mentioned directory and writes the content in the response object using ServletOutputStream and BufferedOutputStream classes.

  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4. public class DisplayImage extends HttpServlet {  
  6.     public void doGet(HttpServletRequest request,HttpServletResponse response)  
  7.              throws IOException  
  8.     {  
  9.     response.setContentType("image/jpeg");  
  10.     ServletOutputStream out;  
  11.     out = response.getOutputStream();  
  12.     FileInputStream fin = new FileInputStream("c:\\test\\java.jpg");  
  14.     BufferedInputStream bin = new BufferedInputStream(fin);  
  15.     BufferedOutputStream bout = new BufferedOutputStream(out);  
  16.     int ch =0; ;  
  17.     while((ch=bin.read())!=-1)  
  18.     {  
  19.     bout.write(ch);  
  20.     }  
  22.     bin.close();  
  23.     fin.close();  
  24.     bout.close();  
  25.     out.close();  
  26.     }  
  27. }