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
| @WebServlet("/downloadServlet") public class DownloadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename=request.getParameter("filename"); String path=this.getServletContext().getRealPath("/img/"+filename); FileInputStream fis=new FileInputStream(path); String mimeType=this.getServletContext().getMimeType(filename); response.setHeader("content-type",mimeType); response.setHeader("content-disposition","attachment;filename="+filename); ServletOutputStream sos=response.getOutputStream(); int len=0; byte[] buff=new byte[1024*8]; while((len=fis.read(buff))!=-1){ sos.write(buff,0,len); } fis.close(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
|