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;
    }

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

相关推荐
闲人编程10 分钟前
Python第三方库IPFS-API使用详解:构建去中心化应用的完整指南
开发语言·python·去中心化·内存·寻址·存储·ipfs
小厂永远得不到的男人13 分钟前
基于 Spring Validation 实现全局参数校验异常处理
java·后端·架构
计算机编程小咖1 小时前
《基于大数据的农产品交易数据分析与可视化系统》选题不当,毕业答辩可能直接挂科
java·大数据·hadoop·python·数据挖掘·数据分析·spark
艾莉丝努力练剑1 小时前
【C语言16天强化训练】从基础入门到进阶:Day 7
java·c语言·学习·算法
CTRA王大大1 小时前
【golang】制作linux环境+golang的Dockerfile | 如何下载golang镜像源
linux·开发语言·docker·golang
老华带你飞1 小时前
校园交友|基于SprinBoot+vue的校园交友网站(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·校园交友网站
自强的小白2 小时前
学习Java24天
java·学习
zhangfeng11332 小时前
以下是基于图论的归一化切割(Normalized Cut)图像分割工具的完整实现,结合Tkinter界面设计及Python代码示
开发语言·python·图论
Ashlee_code3 小时前
香港券商櫃台系統跨境金融研究
java·python·科技·金融·架构·系统架构·区块链
还梦呦3 小时前
2025年09月计算机二级Java选择题每日一练——第五期
java·开发语言·计算机二级