• java生成zip压缩包文件


    生成压缩包工具生成代码

    1. package com.util;
    2. import lombok.SneakyThrows;
    3. import lombok.extern.slf4j.Slf4j;
    4. import org.springframework.util.FileCopyUtils;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. import java.io.BufferedInputStream;
    8. import java.io.BufferedOutputStream;
    9. import java.io.File;
    10. import java.io.FileInputStream;
    11. import java.io.FileOutputStream;
    12. import java.io.IOException;
    13. import java.io.InputStream;
    14. import java.io.OutputStream;
    15. import java.net.URLEncoder;
    16. import java.nio.file.Files;
    17. import java.nio.file.attribute.BasicFileAttributes;
    18. import java.util.Locale;
    19. import java.util.zip.Adler32;
    20. import java.util.zip.CheckedOutputStream;
    21. import java.util.zip.ZipEntry;
    22. import java.util.zip.ZipOutputStream;
    23. /**
    24. * 生成压缩包
    25. */
    26. @Slf4j
    27. public class ZipCompressor {
    28. @SneakyThrows
    29. public static void getZip(String zipName, File zipFile, HttpServletRequest request, HttpServletResponse response, File... files) {
    30. try (
    31. // 作用是为任何OutputStream产生校验和
    32. FileOutputStream fos = new FileOutputStream(zipFile);
    33. // 第一个参数是制定产生校验和的输出流,第二个参数是指定Checksum的类型 (Adler32(较快)和CRC32两种)
    34. CheckedOutputStream cos = new CheckedOutputStream(fos, new Adler32());
    35. // 用于将数据压缩成zip文件格式
    36. ZipOutputStream zos = new ZipOutputStream(cos)
    37. ) {
    38. // 循环根据路径从OSS获得对象,存入临时文件zip中
    39. for (File file : files) {
    40. compressFile(zos, file, file.getName());
    41. }
    42. zos.close();
    43. String header = request.getHeader(CommonConstants.USER_AGENT).toUpperCase(Locale.ROOT);
    44. // IE下载文件名空格变+号问题
    45. zipName = URLEncoder.encode(zipName, CommonConstants.UTF_8);
    46. zipName = zipName.replace("+", "%20");
    47. // 设置响应类型,以附件形式下载文件
    48. response.reset();
    49. response.setContentType("text/plain");
    50. response.setContentType("application/octet-stream; charset=utf-8");
    51. response.setHeader("Location", zipName);
    52. response.setHeader("Cache-Control", "max-age=0");
    53. response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
    54. response.addHeader("Access-Control-Allow-Origin", "*");
    55. response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    56. response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    57. response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
    58. // 下载流封装
    59. try (FileInputStream fis = new FileInputStream(zipFile);
    60. BufferedInputStream bis = new BufferedInputStream(fis);
    61. BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
    62. // 下载zip文件
    63. FileCopyUtils.copy(bis, bos);
    64. // 删除临时zip文件
    65. boolean delete = zipFile.delete();
    66. }
    67. } catch (Exception exception) {
    68. log.error("getZip error: ", exception);
    69. }
    70. }
    71. private static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws IOException {
    72. if (!sourceFile.exists()) {
    73. return;
    74. }
    75. // 若路径为目录(文件夹)
    76. BasicFileAttributes basicFileAttributes = Files.readAttributes(sourceFile.toPath(), BasicFileAttributes.class);
    77. if (basicFileAttributes.isDirectory()) {
    78. // 取出文件夹中的文件(或子文件夹)
    79. File[] fileList = sourceFile.listFiles();
    80. // 若文件夹为空,则创建一个目录进入点
    81. assert fileList != null;
    82. if (fileList.length == 0) {
    83. // 文件名称后跟File.separator表示这是一个文件夹
    84. zos.putNextEntry(new ZipEntry(baseName + File.separator));
    85. // 若文件夹非空,则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩
    86. } else {
    87. for (File file : fileList) {
    88. compressFile(zos, file, baseName + File.separator + file.getName());
    89. }
    90. }
    91. // 若为文件,则先创建目录进入点,再将文件写入zip文件中
    92. } else {
    93. ZipEntry zipEntry = new ZipEntry(baseName);
    94. // 设置ZipEntry的最后修改时间为源文件的最后修改时间
    95. zipEntry.setTime(basicFileAttributes.lastModifiedTime().toMillis());
    96. zos.putNextEntry(zipEntry);
    97. try (FileInputStream fis = new FileInputStream(sourceFile)) {
    98. copyStream(fis, zos);
    99. } catch (Exception exception) {
    100. log.error("输入流关闭异常:", exception);
    101. }
    102. }
    103. }
    104. /**
    105. * 流拷贝
    106. *
    107. * @param inputStream 输入流
    108. * @param outputStream 输出流
    109. */
    110. private static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
    111. int bufferLength = 1024 * 100;
    112. int count;
    113. byte[] buffer = new byte[bufferLength];
    114. while ((count = inputStream.read(buffer, 0, bufferLength)) != -1) {
    115. outputStream.write(buffer, 0, count);
    116. }
    117. outputStream.flush();
    118. }
    119. }

    应用代码

    java

    1. @RequestMapping(value = "/getZip", method = RequestMethod.POST)
    2. public void getZip(@RequestParam("name") String name, HttpServletRequest request, HttpServletResponse response) {
    3. if (StringUtils.isBlank(name)) {
    4. log.info("getZip error: name is not empty");
    5. return;
    6. }
    7. File file = new File("文件夹路径");
    8. File subFile = new File(file, "子文件夹名称");
    9. String zipName = eventName + ".zip";
    10. try {
    11. // 创建临时文件
    12. File zipFile = FileUtil.createTempFile(eventName, ".zip", true);
    13. // 下载文件为zip压缩包
    14. ZipCompressor.getZip(zipName, zipFile, request, response, subFile);
    15. log.info("getZip end.");
    16. } catch (Exception exception) {
    17. log.error("getZip error: ", exception);
    18. } finally {
    19. // 删除生成的文件和文件夹
    20. if (file.exists()) {
    21. try {
    22. FileUtils.forceDelete(file);
    23. } catch (Exception exception) {
    24. log.error("forceDelete error ", exception);
    25. }
    26. }
    27. }
    28. }

    react

    1. jsonSchema2pojo = () => {
    2. const formData = new FormData();
    3. formData.append('name', "名称");
    4. const xhr = new XMLHttpRequest();
    5. xhr.open('POST', apiPrefix + '/getZip', true);
    6. xhr.responseType = 'blob';
    7. xhr.onload = function () {
    8. if (xhr.status === 200) {
    9. let filename
    10. var type = xhr.getResponseHeader('content-type')
    11. // 后台返回了名字则用后台的名字
    12. var contentDisposition = xhr.getResponseHeader('content-disposition')
    13. if (!filename && contentDisposition) {
    14. var idx = contentDisposition.indexOf('filename=')
    15. if (idx > -1) {
    16. filename = decodeURIComponent(contentDisposition.substring(idx + 9))
    17. }
    18. }
    19. var blob = xhr.response
    20. if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    21. window.navigator.msSaveBlob(blob, filename)
    22. } else {
    23. var downloadElement = document.createElement('a')
    24. var href = window.URL.createObjectURL(blob, {
    25. type: type
    26. })
    27. // 创建下载的链接
    28. downloadElement.href = href
    29. // 下载后文件名
    30. downloadElement.download = filename
    31. document.body.appendChild(downloadElement)
    32. // 点击下载
    33. downloadElement.click()
    34. // 下载完成移除元素
    35. document.body.removeChild(downloadElement)
    36. // 释放掉blob对象
    37. window.URL.revokeObjectURL(href)
    38. }
    39. }
    40. }
    41. xhr.send(formData);
    42. }

  • 相关阅读:
    linux12企业实战 -- 56 zabbix常规监控错误汇总
    Netty面试题(三)
    VisualSVN 8.1 Release Notes Date: November 3, 2022
    在嵌入式设计中添加双向I2C数字隔离
    通过Windbg动态调试去捕获C++软件异常的完整过程介绍
    记一次 ClickHouse 性能测试
    详细解读_SpringMvc类型转换&数据格式化&数据验证
    JAVA重写与多态
    pdf转换器是什么东西?看这篇就懂了!
    Mongodb命令行基本操作及增删改查带分页
  • 原文地址:https://blog.csdn.net/NIki_ya/article/details/133687078