温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用SpringBoot将文件打包成zip存放或导出

发布时间:2021-06-12 09:18:15 来源:亿速云 阅读:684 作者:小新 栏目:开发技术

这篇文章主要介绍如何使用SpringBoot将文件打包成zip存放或导出,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

环境准备

其实也没什么准备,准备好Springboot就行,还有几张图片:

如何使用SpringBoot将文件打包成zip存放或导出

将文件打包成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:

如何使用SpringBoot将文件打包成zip存放或导出

调用接口后就会在D盘中新建一个package.zip的压缩包:

如何使用SpringBoot将文件打包成zip存放或导出

可以看到,我打包的文件都在这里,再看看能不能正常显示:

如何使用SpringBoot将文件打包成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:

如何使用SpringBoot将文件打包成zip存放或导出
如何使用SpringBoot将文件打包成zip存放或导出

下载完成后打开看看

如何使用SpringBoot将文件打包成zip存放或导出

以上是“如何使用SpringBoot将文件打包成zip存放或导出”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI