java实现根据url批量下载图片到浏览器

本文介绍了一种方法,即如何通过Java编程实现从多个URL地址批量下载图片资源,并将其打包成一个ZIP文件供用户下载。该过程涉及HTTP请求处理、文件流操作及中文文件名的编码处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /**
     * 给定一组url,将此集合地址下对应的资源下载到浏览器
     *
     * @param urls url地址的集合
     * @throws IOException
     */
public static void downloadPic(List<String> urls, HttpServletResponse response) throws Exception {
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        try {
            String downloadFilename = "教师资格证件照.zip";// 文件的名称
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream;charset=UTF-8");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition","attachment;filename="+downloadFilename);// 设置在下载框默认显示的文件名

            for (String url : urls) {
                String imgName = LocalDateTime.now().toString();
                String suffix = url.substring(url.lastIndexOf("."));
                zos.putNextEntry(new ZipEntry(imgName + suffix));
                InputStream fis = getInputStreamByGet(url);
                byte[] bytes = new byte[1024];
                int len;
                while (true) {
                    assert fis != null;
                    if ((len = fis.read(bytes)) == -1) break;
                    zos.write(bytes, 0, len);
                }
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            zos.flush();
            zos.close();
        }
    }

    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return conn.getInputStream();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值