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
|
public class FilterImage implements Filter
{
private static String IMAGE_REPOSITORY;
@Override
public void init(FilterConfig config) throws ServletException
{
IMAGE_REPOSITORY = config.getInitParameter("IMAGE_REPOSITORY");
}
@Override
public void destroy()
{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
File file = null;
BufferedReader reader = null;
FileReader fileReader = null;
ServletContext sc = null;
try
{
HttpServletRequest _request = (HttpServletRequest)request;
HttpServletResponse _response = (HttpServletResponse)response;
String filePath = _request.getRequestURI();
file = new File(IMAGE_REPOSITORY + filePath.substring(filePath.lastIndexOf("/")));
// Set content type
sc = _request.getSession().getServletContext();
String mime = sc.getMimeType(filePath);
_response.setContentType(mime);
// Set content size
_response.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
ServletOutputStream out = _response.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);
}
in.close();
out.close();
}
catch (Exception e)
{
...
}
finally
{
if (fileReader != null) try { fileReader.close(); } catch (Exception e) {}
if (reader != null) try { reader.close(); } catch (Exception e) {}
}
}
} |
Partager