1 package cn.itcast.download;
2
3 import javax.servlet.ServletException;
4 import javax.servlet.ServletOutputStream;
5 import javax.servlet.annotation.WebServlet;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import java.io.FileInputStream;
10 import java.io.IOException;
11 import java.net.URLEncoder;
12 import java.util.Base64;
13
14 @WebServlet("/download")
15 public class DownloadServlet2 extends HttpServlet {
16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17 //获取资源名
18 String filename = request.getParameter("filename");
19 //获取资源对应输入流
20 FileInputStream fis = new FileInputStream(request.getServletContext().getRealPath("/download/" + filename));
21 //告知类型
22 response.setContentType(request.getServletContext().getMimeType(filename));
23 //告知下载
24 //处理响应头乱码,浏览器兼容性问题
25 String agent = request.getHeader("user-agent");
26 String fileNameEnc = null;
27 if(agent.contains("MSIE")){
28 fileNameEnc = URLEncoder.encode(filename,"UTF-8").replace("+", " ");
29 }else if(agent.contains("Firefox")){
30 fileNameEnc = "=?utf-8?B?"
31 + Base64.getEncoder().encodeToString(filename.getBytes("UTF-8"))
32 + "?=";
33 }else{
34 fileNameEnc = URLEncoder.encode(filename,"UTF-8");
35 }
36 response.setHeader("content-disposition", "attachment;filename=" + fileNameEnc);
37 //获取响应输出流
38 ServletOutputStream sos = response.getOutputStream();
39 //写数据
40 byte[] bys = new byte[1024 * 8];
41 int len;
42 while((len = fis.read(bys)) != -1){
43 sos.write(bys, 0, len);
44 }
45 //释放资源
46 fis.close();
47 }
48
49 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
50 doPost(request, response);
51 }
52 }