1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
|
package org.pbol.uhe.web.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The Image servlet for serving from absolute path.
* @author BalusC
* @link http://balusc.blogspot.com/2007/04/imageservlet.html
*/
@SuppressWarnings("serial")
public class ImageServlet extends HttpServlet {
// Constants ----------------------------------------------------------------------------------
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
// Properties ---------------------------------------------------------------------------------
private String imagePath;
// Actions ------------------------------------------------------------------------------------
protected static Logger logger = Logger.getLogger("ImageProcessing");
public void init() throws ServletException {
// Define base path somehow. You can define it as init-param of the servlet.
this.imagePath = "c:\\repository\\photo";
/*
*
*/
Handler fh = null;
try {
fh = new FileHandler(getClass().getSimpleName()+".log");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.addHandler(fh);
/*
*
*/
logger.log(Level.WARNING, "ImageServlet init");
// In a Windows environment with the Applicationserver running on the
// c: volume, the above path is exactly the same as "c:\images".
// In UNIX, it is just straightforward "/images".
// If you have stored files in the WebContent of a WAR, for example in the
// "/WEB-INF/images" folder, then you can retrieve the absolute path by:
// this.imagePath = getServletContext().getRealPath("/WEB-INF/images");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get requested image by path info.
String requestedImage = request.getPathInfo();
logger.log(Level.WARNING, "ici1");
// Check if file name is actually supplied to the request URI.
if (requestedImage == null) {
// Do your thing if the image is not supplied to the request URI.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
logger.log(Level.WARNING, "ici2");
// Decode the file name (might contain spaces and on) and prepare file object.
File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
// Check if file actually exists in filesystem.
if (!image.exists()) {
// Do your thing if the file appears to be non-existing.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
logger.log(Level.WARNING, "ici3");
// Get content type by filename.
String contentType = getServletContext().getMimeType(image.getName());
// Check if file is actually an image (avoid download of other files by hackers!).
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
if (contentType == null || !contentType.startsWith("image")) {
// Do your thing if the file appears not being a real image.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
logger.log(Level.WARNING, "ici4");
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
logger.log(Level.WARNING, "ici5");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
logger.log(Level.WARNING, "ici6");
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
logger.log(Level.WARNING, "ici7");
} finally {
// Gently close streams.
close(output);
close(input);
logger.log(Level.WARNING, "ici close");
}
}
// Helpers (can be refactored to public utility class) ----------------------------------------
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it.
e.printStackTrace();
}
}
}
} |
Partager