手把手教你用SpringBoot将文件打包成zip存放或导出


Posted in Java/Android onJune 11, 2021

环境准备

其实也没什么准备,准备好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存放或导出的文章就介绍到这了,更多相关SpringBoot将文件打包成zip内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
Java实战之用Swing实现通讯录管理系统
Jun 13 Java/Android
Java常用函数式接口总结
Jun 29 Java/Android
如何给HttpServletRequest增加消息头
Jun 30 Java/Android
实体类或对象序列化时,忽略为空属性的操作
Jun 30 Java/Android
Java 语言中Object 类和System 类详解
Jul 07 Java/Android
JVM钩子函数的使用场景详解
Aug 23 Java/Android
idea以任意顺序debug多线程程序的具体用法
Aug 30 Java/Android
深入解读Java三大集合之map list set的用法
Nov 11 Java/Android
Java由浅入深通关抽象类与接口(下篇)
Apr 26 Java/Android
java版 简单三子棋游戏
May 04 Java/Android
Spring Cloud OAuth2实现自定义token返回格式
Jun 25 Java/Android
SpringBoot项目多数据源及mybatis 驼峰失效的问题解决方法
Jul 07 Java/Android
springboot @ConfigurationProperties和@PropertySource的区别
教你用Java Swing实现自助取款机系统
总结一些Java常用的加密算法
Jun 11 #Java/Android
为什么在foreach循环中JAVA集合不能添加或删除元素
Jun 11 #Java/Android
源码解读Spring-Integration执行过程
浅谈Java实现分布式事务的三种方案
分享一些Java的常用工具
You might like
php access 数据连接与读取保存编辑数据的实现代码
2010/05/12 PHP
检测codeigniter脚本消耗内存情况的方法
2015/03/21 PHP
PHP常用的小程序代码段
2015/11/14 PHP
Laravel6.18.19如何优雅的切换发件账户
2020/06/14 PHP
js使用心得分享
2015/01/13 Javascript
PHPExcel中的一些常用方法汇总
2015/01/23 Javascript
基于JavaScript实现移除(删除)数组中指定元素
2016/01/04 Javascript
基于jQuery实现咖啡订单管理简单应用
2017/02/10 Javascript
zTree树形插件异步加载方法详解
2017/06/14 Javascript
Angular5升级RxJS到5.5.3报错:EmptyError: no elements in sequence的解决方法
2018/04/09 Javascript
angularJs自定义过滤器实现手机号信息隐藏的方法
2018/10/08 Javascript
使用pm2部署node生产环境的方法步骤
2019/03/09 Javascript
微信小程序点击列表跳转到对应详情页过程解析
2019/09/26 Javascript
15 分钟掌握vue-next响应式原理
2019/10/13 Javascript
JavaScript缺少insertAfter解决方案
2020/07/03 Javascript
[02:03]《现实生活中的DOTA2》—林书豪&DOTA2职业选手出演短片
2015/08/18 DOTA
[00:14]护身甲盾
2019/03/06 DOTA
Python构建XML树结构的方法示例
2017/06/30 Python
Python中__slots__属性介绍与基本使用方法
2018/09/05 Python
python tkinter canvas 显示图片的示例
2019/06/13 Python
Win10里python3创建虚拟环境的步骤
2020/01/31 Python
浅谈在JupyterNotebook下导入自己的模块的问题
2020/04/16 Python
关于matplotlib-legend 位置属性 loc 使用说明
2020/05/16 Python
zooplus德国:便宜地订购动物用品、动物饲料、动物食品
2020/05/06 全球购物
博士研究生自我鉴定范文
2013/12/04 职场文书
自荐信格式简述
2014/01/25 职场文书
竞聘演讲稿精彩开头和结尾
2014/05/14 职场文书
学校党员对照检查材料
2014/08/28 职场文书
教师四风问题整改措施
2014/09/25 职场文书
融资合作协议书范本
2014/10/17 职场文书
交通事故死亡赔偿协议书
2014/12/03 职场文书
遗愿清单观后感
2015/06/09 职场文书
小学一年级语文教学反思
2016/03/03 职场文书
使用Django实现商城验证码模块的方法
2021/06/01 Python
常用的MongoDB查询语句的示例代码
2021/07/25 MongoDB
Java完整实现记事本代码
2022/06/16 Java/Android