java实现下载文件压缩包

业务背景:

在开发过程中,我们会遇到需要对文件(单个或多个)进行压缩并下载的功能需求,这里记录一下压缩多个文件的实现过程,或许有更好的方式请大家补充

前端实现一个按钮调下载压缩包的接口

javascript 复制代码
<button icon="download" type="primary" @click="download">
  下载压缩包
<button>

<script>
    download () {
      location.href = faceConfig.basePath + '/download?' +
          '&fileIds=' + paramData.fileIds +   //业务参数,根据实际情况写
    },
</script>

后端接口实现:

controller控制层定义下载压缩包接口

java 复制代码
    @GetMapping("download")
    public void download(String fileIds){
        readService.download(fileIds,getResponse());
    }

定义service服务层接口

java 复制代码
public interface ReadService {

    void download(String fileIds, HttpServletResponse response);
}

定义服务层接口实现类

java 复制代码
@Override
    public void download(String fileIds, HttpServletResponse response) {
        String[] Ids = fileIds.split(",");
        Map map = new HashMap();
        Map bas64Map = new HashMap();
        File[] file = new File[Ids.length];
        File file1 = null;
        OutputStream output = null;
        BufferedOutputStream bufferedOutput = null;
        FileInputStream inStream = null;
        try {
            for (int i = 0; i < Ids.length; i++) {
                // 1.获取到要压缩的文件,这里是自己的业务逻辑,可根据实际情况去写,只要最后能拿到file就行
                Map paramMap = new HashMap();
                paramMap.put("Id", Ids[i]);
                map = certificatePrintReadMapper.getFileInfo(paramMap);
                bas64Map = WaterMarkUtils.createStringMark(map);
                String base64 = (String) bas64Map.get("qj");
                byte[] bytes = decode(base64);
                file1 = new File(Ids[i] + "证书.jpg");
                output = new FileOutputStream(file1);
                bufferedOutput = new BufferedOutputStream(output);
                bufferedOutput.write(bytes);
                // 2。文件放到文件数组里
                file[i] = file1;
                output.close();
                bufferedOutput.close();
            }
            // 3.创建压缩文件,将文件数组进行压缩
            File zip = new File("压缩包名字.zip");// 压缩文件
            zipFiles(file, zip);
            response.setContentType("*/*");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String("压缩包名字.zip".getBytes(), "ISO8859-1"));
            ServletOutputStream outputStream = response.getOutputStream();
            inStream = new FileInputStream(zip);
            byte[] buf = new byte[4096];
            int readLength;
            while (((readLength = inStream.read(buf)) != -1)) {
                outputStream.write(buf, 0, readLength);
            }
            inStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedOutput != null) {
                try {
                    bufferedOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //子方法,压缩文件
    public static void zipFiles(File[] srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        FileInputStream in = null;
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    zipfile), StandardCharsets.UTF_8);
            //File file2 = null;
            for (int i = 0; i < srcfile.length; i++) {
                String filename = srcfile[i].getName();
                in = new FileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(filename));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

//                out.setEncoding("GBK");
                out.closeEntry();
                in.close();

                System.out.println(srcfile[i].delete());
            }
            out.close();
        } catch (IOException e) {
            //e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
    }

    //子方法,将Base64转成字节数组
    public static byte[] decode(String str) {
        byte[] b = null;
        String result = null;
        if (str != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(str);
                // result = new String(b, "utf-8");
            } catch (Exception e) {

            }
        }
        return b;
    }

这样就实现了一个将多个文件进行压缩并下载的功能啦

相关推荐
nice_lcj5201 小时前
Spring 事务:声明式事务怎么生效
java·spring·面试·事务·transactional·传播机制
沐知全栈开发1 小时前
基于Flask的班级信息与班务管理系统设计与实现-毕业设计
java·flask·课程设计
RobinXYuan1 小时前
【Java 字节码探秘】04 总览:索引空间与 17 种 cp_info
java·jvm·源码阅读
vx-程序开发1 小时前
【毕设分享】05253基于Spring+Boot的作业提交与管理系统的设计与实现
java·spring boot·后端·spring·源码·课程设计·大作业
Rain的Java大神之路2 小时前
把 ThreadLocal 换成 ScopedValue 后,请求上下文为什么在子线程里"消失"了?三个边界 + 完整迁移指南(JDK 25)
java·后端·面试
inferno2 小时前
Java正则表达式学习笔记
java·笔记·学习·正则表达式
布莱克6053 小时前
Swift 可选链详解:从语法到实战
开发语言·ios·swift·可选链
会编程的吕洞宾3 小时前
JVM频繁Full GC排查实战_后端定位与调优
java·经验分享·后端
布莱克6053 小时前
Swift 类型转换详解:从基础语法到实战技巧
开发语言·ios·swift·类型转换
木井巳3 小时前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法