springboot将多个文件压缩成zip流并通过ResponseEntity下载-不用将zip保存硬盘

springboot将多个文件压缩成zip流并通过ResponseEntity下载-不用将zip保存硬盘

场景:之前遇到需要请求多个文件同时返回的问题,想到用zip压缩后返回的办法,但是奈何网上全都是先保存硬盘,在返回文件流,或者nginx代理下载文件的方式,亦或者是用其他种方式,反正最终都没有满意的。

  • 以下是通过使用springboot的ResponseEntity来直接返回字节码的方式,将多个文件压缩人zip流,然后转换成字节返回。

上代码

1、ZipUtils工具类

public class ZipUtils {
    /**
     * 文件批量压缩,不保存实际位置
     *
     * @param byteList         文件字节码Map,k:fileName,v:byte[]
     * @param byteOutPutStream 字节输出流
     */
    public static void batchFileToZIP(Map<String, byte[]> byteList, ByteArrayOutputStream byteOutPutStream) {

        ZipOutputStream zipOutputStream = new ZipOutputStream(byteOutPutStream);

        try {
            for (Map.Entry<String, byte[]> entry : byteList.entrySet()) {
                //写入一个条目,我们需要给这个条目起个名字,相当于起一个文件名称
                zipOutputStream.putNextEntry(new ZipEntry(entry.getKey()));
                zipOutputStream.write(entry.getValue());
            }
            zipOutputStream.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2、ResponseEntity封装工具类

public class ResponseEntityUtils {
    /**
     * ResponseEntity下载zip文件
     *
     * @param fileName 文件名
     * @param byteFile 字节码
     * @param response response
     * @return
     */
    public static ResponseEntity<byte[]> buildByteFileResponse(String fileName, byte[] byteFile, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            return ResponseEntity.ok().body(byteFile);
        } catch (Exception e) {
            LOGGER.warn("Warning", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("下载失败.".getBytes());
        }
    }
}

3、使用方法(可以当做controller)

Map<String, byte[]> byteFileMap = new HashMap<>();
byteFileMap.put(“testfile.txt”, "我是文件内容".getBytes());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipUtils.batchFileToZIP(byteFileMap, byteArrayOutputStream);

String zipFileName = String.format("%s%s", LocalDateTime.now(), ".zip");

HttpServletResponse response = new HttpServletResponse();

return ResponseEntityUtils.buildByteFileResponse(zipFileName, byteArrayOutputStream.toByteArray(), response);
  • 以上就是整个调用过程

感谢大佬的文章给的启发,参考了文章后进行了提炼。
附上大佬文章:https://blog.csdn.net/u013521220/article/details/102621784

Q.E.D.

  • 9
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
Spring Boot提供了一个非常方便的方式来压缩文件,可以使用Java自带的ZipOutputStream来实现。 你可以编写一个简单的工具类,将一个文件夹下的所有文件压缩成一个zip文件,代码如下: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtils { public static void zipFolder(String srcFolder, String destZipFile) throws IOException { ZipOutputStream zip = null; FileOutputStream fileWriter = null; fileWriter = new FileOutputStream(destZipFile); zip = new ZipOutputStream(fileWriter); addFolderToZip("", srcFolder, zip); zip.flush(); zip.close(); } private static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws IOException { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } } private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException { File folder = new File(srcFolder); for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip); } } } } ``` 上述代码中,`zipFolder`方法接收两个参数:源文件夹的路径和目标zip文件的路径。该方法首先打开一个ZipOutputStream,然后使用`addFolderToZip`方法从源文件夹中递归添加所有文件和子文件夹。 使用该工具类,你可以压缩任何文件夹,例如: ```java ZipUtils.zipFolder("/path/to/folder", "/path/to/archive.zip"); ``` 这会压缩`/path/to/folder`下的所有文件和子文件夹,并将它们保存在`/path/to/archive.zip`文件中。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水豚少年的码农生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值