Java 多文件压缩以及zip文件流下载,以及前端请求

767 阅读1分钟

1、多文件压缩,功能代码如下:

/**
 * 多文件压缩下载
 * @param list (map里面存每个文件的信息:URL:文件路径;NAME:单个文件下载后的文件名)
 * @param attachmentName 压缩包的名称
 * @param response
 * @return
 * @throws Exception
 */
public static boolean downLoadMany(List<File> list, String attachmentName, HttpServletResponse response) throws Exception {
   boolean bool = false;
   BufferedInputStream bis = null;
   // 生成一个文件包
   String zipPath = AppConst.UPLOAD_PATH + attachmentName + ".zip";// 压缩路径
   try {
      ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath));
      String fileName = "";
      for (int i = 0; i < list.size(); i++) {
         String n = list.get(i).getName();
         fileName = n + n.substring(n.lastIndexOf("."));
         bis = new BufferedInputStream(new FileInputStream(list.get(i)));
         ZipEntry zipEntry = new ZipEntry(fileName);
         zipOutputStream.putNextEntry(zipEntry);
         // 读取文件内容
         byte[] buffer = new byte[1024]; // 创建存放输入流的缓冲
         int num = -1; // 读入的字节数
         while ((num = bis.read(buffer)) > 0) {
            zipOutputStream.write(buffer, 0, num);
         }
         zipOutputStream.closeEntry();
         bis.close();
      }
      zipOutputStream.close();
      bool = true;
   } catch (Exception e) {
      e.printStackTrace();
      bool = false;
   }
   return bool;
}

2、zip下载

public static void downLoad_HTTP(HttpServletResponse response) {
      String zipPath = "绝对路径/images1.zip";
      try {
         File file = new File(zipPath);
         if (!file.exists()) return;
         String name = URLEncoder.encode(file.getName(), "UTF-8");
         // 以流的形式下载文件。
         BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
         byte[] buffer = new byte[fis.available()];
         fis.read(buffer);
         fis.close();
         // 清空response
         response.reset();
         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
         response.setContentType("application/octet-stream");
         response.addHeader("Access-Control-Allow-Origin","*");
         response.setHeader("Content-Disposition", "attachment;filename=" + name);
         toClient.write(buffer);
         toClient.flush();
         toClient.close();
         file.delete();
      }
      catch (IOException ex) {
         ex.printStackTrace();
      }
   }

3、前端请求代码,其中responseType是重点,这是个巨坑

export const cutImageBase64 = (data = {}) => {
  return axios.request({
    url: '/user/cutImageBase64',
    method: 'post',
    data,
    responseType: 'blob'
  })
}