多个URL文件下载并打包成zip文件

反卷王,因为需要才写了此代码

一、代码实例

// 根据url下载文件打包zip
private void getZip(HttpServletResponse response, String dbUrl)throws Exception{
        //处理文件
        String[] dbUrls = dbUrl.split(",");
        String zipName = new Date().getTime() + ".zip";
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + zipName);
        response.setCharacterEncoding("utf-8");
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (String iUrl : dbUrls) {
                URL url = new URL(iUrl);// 读取url信息
                zipOut.putNextEntry(new ZipEntry(FilenameUtils.getName(iUrl)));// 创建url文件
                InputStream in = new BufferedInputStream(url.openStream());// 读取url文件信息
                zipOut.write(readInputStream(in));//把url文件写入zip中

                zipOut.closeEntry();// 关闭入口
                in.close(); // 关闭连接
            }
        } catch (IOException e) {
            throw new Exception("导出压缩包失败");
        }
        try {
            // 声明一个工作薄  创建新的文件
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("ERROR:Download failed" + e.getMessage());
        }
    }
    
	//根据文件链接把文件下载下来并且转成字节码
    public byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

二、实例

列如:http://localhost:8089/lcyj/information/getZip?dbUrl=url-A,url-B
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值