Skip to content

Latest commit

 

History

History
43 lines (38 loc) · 1.27 KB

下载文件.md

File metadata and controls

43 lines (38 loc) · 1.27 KB

下载文件

思路:

  1. 设置返回的内容格式为二进制
  2. 设置下载后的文件名称
  3. 读取文件流并写出Response的输出流
  4. 关闭文件输入流
  /**
   * 下载文件
   *
   * @param filepath 下载文件的路径
   * @param filename 下载后文件的名称
   */
  public static void download(HttpServletResponse response, String filepath, String filename) {
    InputStream inputStream = null;
    try {
      // 设置返回类型为二进制
      response.setHeader("content-type", "application/octet-stream");
      response.setContentType("application/octet-stream");
      // 设置下载后的文件名称
      response.setHeader("Content-Disposition",
          "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
      // 写出二进制数据
      OutputStream outputStream = response.getOutputStream();
      inputStream = new FileInputStream(new File(filepath));
      int len;
      byte[] data = new byte[1024];
      while ((len = inputStream.read(data)) != -1) {
        outputStream.write(data, 0, len);
      }
      outputStream.flush();

    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      IoUtil.close(inputStream);
    }
  }