根据url读取文件信息下载zip文件

前言

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。
在这里插入图片描述


这是给大家介绍的java 根据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;
    }

二、url传值通过,隔开
传值方式可以通过这个参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java毕设王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值