In this instance, we are making use of FileInputStream class to study images and the ServletOutputStream class for writing this image content as a reply. In this we used the BufferedInputStream and BufferedOutputStream class, to make the performance faster.
You require to make use of the content type image/jpeg.
We are presuming that you already have a java.jpg image inside the c:\test directory, in this example. You can switch the location correspondingly.
To produce this application, three files are created:
This file makes a link that supplicates the servlet. Servlet1 is the Url pattern of the Servlet.
<a href="servlet1">click for photo</a>
This servlet class studies the image from the given directory and writes down the content in the replying object by making use of ServletOutputStream and BufferedOutputStream classes.
package com.javatpoint; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayImage extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException { response.setContentType("image/jpeg"); ServletOutputStream out; out = response.getOutputStream(); FileInputStream fin = new FileInputStream("c:\\test\\java.jpg"); BufferedInputStream bin = new BufferedInputStream(fin); BufferedOutputStream bout = new BufferedOutputStream(out); int ch =0; ; while((ch=bin.read())!=-1) { bout.write(ch); } bin.close(); fin.close(); bout.close(); out.close(); } }
download this example (developed using Myeclipse IDE)