Wednesday, January 9, 2008

Displaying an Image from Servlet

package com.shailesh;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet implements Servlet {
    /**
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
    }

    /**
     * 
     * 
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest arg0,
     *      HttpServletResponse arg1)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 
     * 
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest arg0,
     *      HttpServletResponse arg1)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        File file = new File("c:\\myImage.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        int i = 0;
        byte[] buffer = new byte[1024];
        while ((= fileInputStream.read(buffer)) >= 0) {
            response.getOutputStream().write(buffer, 0, i);
        }
    }

}

No comments: