手把手教你用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 相关文章推荐
MybatisPlus代码生成器的使用方法详解
Jun 13 Java/Android
新手入门Jvm-- JVM对象创建与内存分配机制
Jun 18 Java/Android
Java Dubbo框架知识点梳理
Jun 26 Java/Android
jackson json序列化实现首字母大写,第二个字母需小写
Jun 29 Java/Android
总结Java对象被序列化的两种方法
Jun 30 Java/Android
浅谈spring boot使用thymeleaf版本的问题
Aug 04 Java/Android
Java数据开发辅助工具Docker与普通程序使用方法
Sep 15 Java/Android
Mybatis是这样防止sql注入的
Dec 06 Java/Android
JavaCV实现照片马赛克效果
Jan 22 Java/Android
SpringBoot中HttpSessionListener的简单使用方式
Mar 17 Java/Android
Java对文件的读写操作方法
Apr 29 Java/Android
Java实现添加条码或二维码到Word文档
Jun 01 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
php5新改动之短标记启用方法
2008/09/11 PHP
php 获取select下拉列表框的值
2010/05/08 PHP
解析左右值无限分类的实现算法
2013/06/20 PHP
PHP pthreads v3下worker和pool的使用方法示例
2020/02/21 PHP
PHP实现文件上传后台处理脚本
2020/03/04 PHP
JQuery 学习笔记 element属性控制
2009/07/23 Javascript
jquery获取当前日期的方法
2015/01/14 Javascript
深入浅析JavaScript中的Function类型
2016/07/09 Javascript
jQuery Validate让普通按钮触发表单验证的方法
2016/12/15 Javascript
jQuery EasyUI Panel面板组件使用详解
2017/02/28 Javascript
jQuery自定义多选下拉框效果
2017/06/19 jQuery
Angular4学习笔记之实现绑定和分包
2017/08/01 Javascript
jQuery实现火车票买票城市选择切换功能
2017/09/15 jQuery
Vue指令之 v-cloak、v-text、v-html实例详解
2019/08/08 Javascript
通过实例了解JS执行上下文运行原理
2020/06/17 Javascript
[02:17]快乐加倍!DOTA2食人魔魔法师至宝+迎霜节活动上线
2019/12/22 DOTA
Python中设置变量访问权限的方法
2015/04/27 Python
动感网页相册 python编写简单文件夹内图片浏览工具
2016/08/17 Python
名片管理系统python版
2018/01/11 Python
Python中实现单例模式的n种方式和原理
2018/11/14 Python
Python Numpy库常见用法入门教程
2020/01/16 Python
python GUI库图形界面开发之PyQt5打开保存对话框QFileDialog详细使用方法与实例
2020/02/27 Python
使用sklearn的cross_val_score进行交叉验证实例
2020/02/28 Python
Python面向对象程序设计之类和对象、实例变量、类变量用法分析
2020/03/23 Python
Python 如何创建一个简单的REST接口
2020/07/30 Python
jupyter 添加不同内核的操作
2021/02/06 Python
台湾旅游网站:雄狮旅游网
2017/08/16 全球购物
美国领先的家庭健康检测试剂盒提供商:LetsGetChecked
2019/03/18 全球购物
俄罗斯小米家用电器、电子产品和智能家居商店:Poood.ru
2020/04/03 全球购物
销售主管岗位职责范本
2014/02/14 职场文书
爱祖国演讲稿
2014/05/04 职场文书
求职自我推荐信
2015/03/24 职场文书
教师网络培训心得体会
2016/01/09 职场文书
《秋天的雨》教学反思
2016/02/19 职场文书
Spring Boot 启动、停止、重启、状态脚本
2021/06/26 Java/Android
总结三种用 Python 作为小程序后端的方式
2022/05/02 Python