Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output an image file from a servlet [duplicate]

Tags:

java

servlets

How to serve an image, stored on my hard drive, in a servlet?
For Example:
I have an image stored in path 'Images/button.png' and I want to serve this in a servlet with the URL file/button.png.

like image 442
Devashish Dixit Avatar asked Dec 24 '11 09:12

Devashish Dixit


2 Answers

Here is the working code:

 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

      ServletContext cntx= req.getServletContext();
      // Get the absolute path of the image
      String filename = cntx.getRealPath("Images/button.png");
      // retrieve mimeType dynamically
      String mime = cntx.getMimeType(filename);
      if (mime == null) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      resp.setContentType(mime);
      File file = new File(filename);
      resp.setContentLength((int)file.length());

      FileInputStream in = new FileInputStream(file);
      OutputStream out = resp.getOutputStream();

      // Copy the contents of the file to the output stream
       byte[] buf = new byte[1024];
       int count = 0;
       while ((count = in.read(buf)) >= 0) {
         out.write(buf, 0, count);
      }
    out.close();
    in.close();

}
like image 52
Jama A. Avatar answered Oct 03 '22 21:10

Jama A.


  • map a servlet to the /file url-pattern
  • read the file from disk
  • write it to response.getOutputStream()
  • set the Content-Type header to image/png (if it is only pngs)
like image 41
Bozho Avatar answered Oct 03 '22 21:10

Bozho