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
| @WebServlet("/ServletDownload") public class ServletDownload extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); String filename = request.getParameter("filename"); ServletContext context = this.getServletContext(); String realPath = context.getRealPath("/img/" + filename);
FileInputStream fs = new FileInputStream(realPath); String mimeType = context.getMimeType(filename); response.setContentType(mimeType);
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { filename = URLEncoder.encode(filename, "UTF-8"); }else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) { filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); } response.setHeader("content-disposition","attachment;filename="+filename); ServletOutputStream outputStream = response.getOutputStream(); byte[] bytes = new byte[1024 * 8]; int len = 0; while((len = fs.read(bytes)) != -1){ outputStream.write(bytes,0,len); } fs.close(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
|