文件下载案例

文件下载案例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<a id="tu" href="/img/3.jpg">图片</a>
<hr>
<a id="tu2" href="/downloadServlet?filename=3.jpg">图片2</a>
<script>
  window.onload = function () {
      var tu = document.getElementById("tu");
      tu.onclick = function () {

      }
  }
</script>
</body>
</html>
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      this.doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.setCharacterEncoding("utf-8");
      resp.setContentType("text/html;charset=utf-8");
      String contextPath = req.getContextPath();
      //1、获取请求参数,文件名
      String filename = req.getParameter("filename");
      System.out.println("filename---"+filename);
      //2使用字节输入流加载文件进内存
      //2.1 找到文件服务器路径
      ServletContext servletContext = this.getServletContext();
      String realPath = servletContext.getRealPath("/img/" + filename);
      System.out.println("realPath--"+realPath);
      //2.2使用字节流关联
      FileInputStream fis = new FileInputStream(realPath);

      //3设置response响应头
      //3.1设置相应头类型,content-type
      String mimeType = servletContext.getMimeType(filename);
      System.out.println("mimeType---"+mimeType);
      resp.setHeader("content-type",mimeType);
      //3.2设置响应头打开方式content-disposition
      resp.setHeader("content-disposition","attachment;finame="+filename);
      //4将输入流的数据写入到输出流
      ServletOutputStream sos = resp.getOutputStream();
      byte[] bytes = new byte[1024 * 8];
      int len = 0;
      while ((len = fis.read(bytes)) != -1){
          sos.write(bytes,0,len);
      }
      if (fis != null){
          fis.close();
      }
  }
}
原文地址:https://www.cnblogs.com/lxy522/p/12937134.html