首先确定HTML页面上的编码格式 我这里是UTF-8

  1. <meta http-equiv="content-type" content="text/html;charset=utf-8">
  • 创建类继承HttpServlet ;
  • 重写doGet或doPost,具体使用哪个看业务需求;
    代码如下:
  1. import sun.misc.BASE64Encoder;
  2. import javax.servlet.ServletContext;
  3. import javax.servlet.ServletOutputStream;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.FileInputStream;
  9. import java.io.IOException;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.URLEncoder;
  12. import java.nio.charset.StandardCharsets;
  13. /**
  14. * Created with IntelliJ IDEA.
  15. * Description:
  16. *
  17. * @author: GanZiB
  18. * Date: 2020-08-24
  19. * Time: 10:16
  20. */
  21. @WebServlet("/download")
  22. public class DownloadServlet extends HttpServlet {
  23. @Override
  24. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  25. //1.获取文件名
  26. String fileName = req.getParameter("fileName");
  27. //2.使用字节输入流加载文件进内存
  28. //2.1找到文件服务器路径
  29. ServletContext servletContext = req.getServletContext();
  30. String realPath = servletContext.getRealPath("/res/" + fileName);
  31. //2.2使用字节流关联
  32. FileInputStream fis = new FileInputStream(realPath);
  33. //3.设置response响应头
  34. //3.1设置响应头类型:content-type
  35. String agent = req.getHeader("user-agent");
  36. String mimeType = servletContext.getMimeType(fileName);
  37. resp.setHeader("content-type", mimeType);
  38. //3.2设置响应头打开方式:content-disposition
  39. resp.setHeader("content-disposition", "attachment;filename=" + getFileName(agent,fileName));
  40. //4.将输入流数据写出到输出流中
  41. ServletOutputStream sos = resp.getOutputStream();
  42. byte[] buff = new byte[1024 * 8];
  43. int len = 0;
  44. while ((len = fis.read(buff)) != -1) {
  45. sos.write(buff, 0, len);
  46. }
  47. fis.close();
  48. }
  49. /**
  50. * 中文乱码适配不同浏览器
  51. */
  52. public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
  53. if (agent.contains("MSIE")) {
  54. // IE
  55. filename = URLEncoder.encode(filename, "utf-8");
  56. filename = filename.replace("+", " ");
  57. } else if (agent.contains("Firefox")) {
  58. //火狐
  59. BASE64Encoder base64Encoder = new BASE64Encoder();
  60. filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes(StandardCharsets.UTF_8)) + "?=";
  61. }else {
  62. filename = URLEncoder.encode(filename,"utf-8");
  63. }
  64. return filename;
  65. }
  66. }
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. </head>
  5. <body>
  6. <a href="/download?fileName=图片1.jpg">图片下载</a>
  7. </body>
  8. </html>