Java downloads multiple files to memory and compresses the file package and returns it without saving it to local packaging and compression.

Scenes

Download files from other servers, package and compress these files and return them to the browser. I don’t want to download the file locally and then package and compress it, so I use memory streaming.

plan

/** 入参:urlList -- 多个文件下载地址 ; filename -- 压缩包名称.zip */

// 压缩包内文件夹名称
String folderName = FilenameUtils.getBaseName(filename);
// 下载并压缩
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(bos)) {
    
    
  for (String url : urlList) {
    
    
    ZipEntry zipEntry = new ZipEntry(folderName + "/" + FilenameUtils.getName(url));
    zos.putNextEntry(zipEntry);
    try {
    
    
      Request request = OkHttpClientUtil.requestBuilder(url).get().build();
      Response response = OkHttpClientUtil.send(request);
      ResponseBody body = response.body();
      IOUtils.copy(body.byteStream(), zos);
      zos.flush();
      zos.closeEntry();
    } catch (IOException e) {
    
    
      throw new FileException("文件下载失败", e, ServiceResponseStatus.RUNTIME_ERROR);
    }
  }
  zos.finish();
  httpServletResponse.addHeader(
      "content-disposition",
      "attachment;filename=" + new String(filename.getBytes(), StandardCharsets.ISO_8859_1));
  OutputStream os = httpServletResponse.getOutputStream();
  IOUtils.copy(new ByteArrayInputStream(bos.toByteArray()), os);
  os.close();
} catch (IOException e) {
    
    
  throw new FileException("xx文件压缩失败", e, ServiceResponseStatus.RUNTIME_ERROR);
}

Guess you like

Origin blog.csdn.net/ZHAI_KE/article/details/128074922