当前位置:   article > 正文

SpringBoot导出压缩zip文件(doc版本)_springboot导出zip文件

springboot导出zip文件

通用组合数据代码

  1. public void downloadZip(HttpServletResponse response) {
  2. List<ExportData> dataList= new ArrayList<>();
  3. //开始压缩导出
  4. String fileName = "download.zip";
  5. response.reset();
  6. response.setCharacterEncoding("UTF-8");
  7. response.setContentType("application/octet-stream");
  8. response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
  9. response.setHeader("Access-Control-Allow-Origin", "*");
  10. byte[] dataByteArr;
  11. if (CollectionUtil.isNotEmpty(dataList)) {
  12. try {
  13. dataByteArr = zipFile(dataList);
  14. response.getOutputStream().write(dataByteArr);
  15. response.flushBuffer();
  16. } catch (Exception e) {
  17. log.error("压缩zip数据出现异常", e);
  18. e.printStackTrace();
  19. }
  20. }
  21. }

压缩文件

  1. /**
  2. * zip文件
  3. *
  4. * @param dataList 数据列表
  5. * @return {@link byte[]}
  6. */
  7. public byte[] zipFile(List<ExportData> dataList) throws IOException {
  8. // 将字节写到一个字节输出流里
  9. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  10. try (ZipOutputStream out = new ZipOutputStream(baos)) {
  11. // 创建zip file in memory
  12. for (ExportData data: dataList) {
  13. ZipEntry entry = new ZipEntry("文件名.doc");
  14. out.putNextEntry(entry);
  15. out.write(data.getContent().getBytes(StandardCharsets.UTF_8));
  16. out.closeEntry();
  17. }
  18. baos.close();
  19. } catch (IOException e) {
  20. log.error("压缩zip数据出现异常", e);
  21. throw new RuntimeException("压缩zip包出现异常");
  22. } finally {
  23. baos.close();
  24. }
  25. return baos.toByteArray();
  26. }

 前端代码 请求接口带上"blob" 

responseType: "blob",

  res就是后端返回的流

  1. const blob = new Blob([res], { type: "application/zip" });
  2. const fileName = `批量下载`;
  3. if ("download" in document.createElement("a")) {
  4. // 非IE下载
  5. const elink = document.createElement("a");
  6. elink.download = fileName;
  7. elink.style.display = "none";
  8. elink.href = window.URL.createObjectURL(blob);
  9. document.body.appendChild(elink);
  10. elink.click();
  11. window.URL.revokeObjectURL(elink.href); // 释放URL 对象
  12. document.body.removeChild(elink);
  13. } else {
  14. // IE10+下载
  15. navigator.msSaveBlob(blob, fileName);
  16. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/984670
推荐阅读
相关标签
  

闽ICP备14008679号