package com.cv.servlet.download;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* Servlet implementation class ImageServlet
*
* @author Chandra Vardhan
*
*/
public class ImageServlet extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger(ImageServlet.class);
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImageServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LOGGER.info("Entered into doGet(--) of ImageServlet class... ");
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
String pathToWeb = getServletContext().getRealPath("/");
LOGGER.info("Context path of the application is : " + pathToWeb);
File file = new File(pathToWeb
+ request.getParameter("filename") + ".jpg");
// First way to read and write content to the output stream
/*
* FileInputStream in = new FileInputStream(file); int size =
* in.available(); byte[] content = new byte[size]; in.read(content);
* out.write(content); in.close();
*/
LOGGER.info("Jpg file path is : " + file.getPath());
// Second way to read and write content to the output stream
BufferedImage bi = ImageIO.read(file);
boolean write = ImageIO.write(bi, "jpg", out);
if(write) {
LOGGER.info("Jpg file content written to the browser successfully...");
}
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LOGGER.info("Entered into doPost(--) of ImageServlet class... ");
doGet(request, response);
}
} |
No comments:
Post a Comment