SpringBoot将文件打包成zip存放或导出

前言

相信各位看官在工作中都会遇到过要把多个文件打包成一个压缩文件然后导出,或者将文件打包成Zip存放,这就来上代码,废话不多说。

环境准备

其实也没什么准备,准备好Springboot就行,还有几张图片:
在这里插入图片描述

将文件打包成Zip存放

代码

Controller代码:

@RequestMapping("/zip")
@RestController
public class ZipController {

    /**
     * 将文件打包成zip并存放在特定位置
     */
    @PostMapping("package")
    public void packageFileToZip() throws IOException {
        // 为了方便我直接将文件地址写好了,各位可以根据自己的情况修改
        String[] filePath = new String[]{"E:\\ykds\\1068128498917799516.jpg", "E:\\ykds\\1068128498917917980.jpg", "E:\\ykds\\1068128498917807874.jpg"};
        // 将需要打包的文件都放在一个集合中
        List<File> fileList = new ArrayList<>();
        for (String s : filePath) {
            File file = new File(s);
            fileList.add(file);
        }
        // 先在D盘创建一个压缩包
        File zipFile = new File("D:\\package.zip");
        if(!zipFile.exists())
            zipFile.createNewFile();
        // 将package.zip的File对象传到toZip对象中
        ZipUtils.toZip(fileList, zipFile);
    }
}

ZipUTils工具类代码

public class ZipUtils {

    /**
     * 把文件集合打成zip压缩包
     * @param srcFiles 压缩文件集合
     * @param zipFile  zip文件名
     * @throws RuntimeException 异常
     */
    public static void toZip(List<File> srcFiles, File zipFile) throws IOException {
        if(zipFile == null){
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            return;
        }
        ZipOutputStream zos = null;
        FileOutputStream out = new FileOutputStream(zipFile);
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                // 读取文件并写入到zip中
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                    zos.flush();
                }
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (zos != null) {
                zos.close();
            }
        }
    }
}

测试

代码打好了,接下来测试下,打开熟悉的postman:
在这里插入图片描述
调用接口后就会在D盘中新建一个package.zip的压缩包:
在这里插入图片描述
可以看到,我打包的文件都在这里,再看看能不能正常显示:
在这里插入图片描述
very good!

将文件打包成zip并导出

上面的方法只是将压缩包保存在本地,如果需要导出的话代码有点不一样。

代码

Controller代码:

	/**
     * 将文件打包成zip并下载
     */
    @PostMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里还是和上面一样
        String[] filePath = new String[]{"E:\\ykds\\1068128498917799516.jpg", "E:\\ykds\\1068128498917917980.jpg", "E:\\ykds\\1068128498917807874.jpg"};
        List<File> fileList = new ArrayList<>();
        for (String s : filePath) {
            File file = new File(s);
            fileList.add(file);
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");
        ZipUtils.downloadZip(response.getOutputStream(), fileList);
    }

ZipUtils工具类代码

public static void downloadZip(OutputStream outputStream, List<File> fileList){
        BufferedInputStream bufferedInputStream = null;
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(outputStream);
            for (File file : fileList) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buf = new byte[BUFFER_SIZE];
                int len;
                FileInputStream in = new FileInputStream(file);
                while ((len = in.read(buf)) != -1) {
                    zipOutputStream.write(buf, 0, len);
                    zipOutputStream.flush();
                }
            }
            zipOutputStream.flush();
            zipOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (zipOutputStream != null ) {
                    zipOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

测试

还是用postman:
在这里插入图片描述
在这里插入图片描述
下载完成后打开看看
在这里插入图片描述
very good!

结尾

zip的分享就到这里啦,各位喜欢的话可以点个赞哦!

  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
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`文件中。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值