JAVA根据图片路径下载图片并写入ZIP

本文介绍了一种使用Java批量下载网络上的图片,并将这些图片压缩成一个ZIP文件供用户下载的方法。此过程涉及使用多线程加速下载、处理中文文件名乱码及创建ZipOutputStream来生成ZIP文件。
 public void downloadPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
     
        List<Map<String, Object>> allSysApp = new ArrayList<>();
        List<String> imgUrls = new ArrayList<>();
        allSysApp.parallelStream().limit(3).forEach(m -> imgUrls.add((String) m.get("logo_img")));
        try {
            String downloadFilename = "中文.zip";//文件的名称
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            String[] files = new String[imgUrls.size()];
            imgUrls.toArray(files);
            for (int i = 0; i < files.length; i++) {
                String url = files[i];
                zos.putNextEntry(new ZipEntry("temp_download" + File.separator + i + ".jpg"));
                InputStream fis = getInputStreamByGet(url);
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
            }
            zos.flush();
            zos.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    // 通过get请求得到读取器响应数据的数据流
    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) {
                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 得到图片字节流 数组大小
     * */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }
以下是一个使用 Java 从 HTTP URL 下载图片将其放入 ZIP 文件的示例代码: ```java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ImageDownloadAndZip { public static void main(String[] args) { String[] imageUrls = { "http://example.com/image1.jpg", "http://example.com/image2.jpg" }; String zipFilePath = "images.zip"; try (ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath)))) { for (int i = 0; i < imageUrls.length; i++) { String imageUrl = imageUrls[i]; String imageName = "image" + (i + 1) + ".jpg"; URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream())) { ZipEntry zipEntry = new ZipEntry(imageName); zipOut.putNextEntry(zipEntry); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { zipOut.write(buffer, 0, bytesRead); } zipOut.closeEntry(); } } } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码实现了从 HTTP URL 下载图片将其放入 ZIP 文件的功能。首先,定义了一个包含图片 URL 的数组和 ZIP 文件路径。然后,使用 `ZipOutputStream` 创建一个 ZIP 文件输出流。接着,遍历图片 URL 数组,对于每个 URL,使用 `HttpURLConnection` 打开连接获取输入流。将每个图片作为一个 `ZipEntry` 放入 ZIP 文件中,图片数据写入 ZIP 文件
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值