Friday, April 23, 2010

A Servlet which sends back an image file

This is a servlet which sends back a image read from a File or a Database.You can map the servlet to a suitable URL in Web.xml

import java.awt.*;
import java.io.*;

import javax.imageio.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExternalImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExternalImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       
        int read = 0;
        byte[] bytes = new byte[1024];
        FileInputStream fis = null;
        OutputStream os = null;         

        try {

          File image = new File("C:/sample.jpg");     
          response.setContentType("image/jpg");         
         
          // If I add this, the browser will prompt me to Open or Save the file
          //response.setHeader("Content-Disposition", "attachment;image=\"" + image + "\"");

          fis = new FileInputStream(image);
          os = response.getOutputStream();

          while((read = fis.read(bytes)) != -1){
              os.write(bytes,0,read);
          }
         
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {
             os.flush();
             os.close();
        }
   
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }   

}

No comments: