Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.armhold.content;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.DataInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.TimeZone;
- /**
- */
- public class ContentServlet extends HttpServlet {
- public static final int BUFSIZE = 8192;
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
- doDownload(res, mapRequestToFile(req));
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
- doGet(req, res);
- }
- protected File mapRequestToFile(HttpServletRequest req) throws ServletException {
- String path = req.getParameter("resource");
- if (path == null || path.equals("")) {
- throw new ServletException("no resource parameter specified");
- }
- if (path.contains("..")) throw new ServletException("illegal path");
- File contentDir = new File("content");
- return new File(contentDir, path);
- }
- protected void doDownload(HttpServletResponse res, File file) throws IOException {
- int length;
- ServletOutputStream op = res.getOutputStream();
- ServletContext context = getServletConfig().getServletContext();
- String mimetype = context.getMimeType(file.getAbsolutePath());
- SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
- // force it to GMT because NSDateFormatter on iPhone does not totally
- // support the standard
- TimeZone gmtTime = TimeZone.getTimeZone("GMT");
- df.setTimeZone(gmtTime);
- Date lastModified = new Date(file.lastModified());
- res.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
- res.setContentLength((int) file.length());
- res.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
- res.setHeader("Last-Modified", df.format(lastModified));
- res.setHeader("Last-Modified-in-millis", "" + file.lastModified());
- byte[] buf = new byte[BUFSIZE];
- DataInputStream in = new DataInputStream(new FileInputStream(file));
- while ((length = in.read(buf)) != -1) {
- op.write(buf, 0, length);
- }
- in.close();
- op.flush();
- op.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment