java实现下载文件压缩包

业务背景:

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

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

<button icon="download" type="primary" @click="download">
  下载压缩包
<button>

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

后端接口实现:

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

    @GetMapping("download")
    public void download(String fileIds){
        readService.download(fileIds,getResponse());
    }

定义service服务层接口 

public interface ReadService {

    void download(String fileIds, HttpServletResponse response);
}

定义服务层接口实现类 

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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现单个压缩包下载,通常可以通过HTTP或HTTPS协议来获取远程服务器上的文件,并使用`java.net.URL`和`java.io`包中的工具来处理下载过程。以下是一个简单的示例,使用`java.net.URLConnection`下载ZIP文件: ```java import java.io.*; import java.net.URL; public class ZipDownloadExample { public static void main(String[] args) { try { // 假设URL地址为远程zip文件的链接 String urlString = "http://example.com/download.zip"; URL url = new URL(urlString); // 创建URL连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); // 设置允许输出流 // 获取响应码,检查是否成功 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 打开输入和输出流 InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream("downloaded.zip"); // 下载后的本地文件路径 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 关闭流 inputStream.close(); outputStream.close(); System.out.println("Download complete."); } else { System.out.println("Error: " + responseCode); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个例子假设下载的是ZIP文件,如果需要下载其他类型的压缩包(如tar.gz),只需要根据需要调整下载文件名和解压方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值