根据图片URL下载到压缩包

该代码示例展示了如何使用Java处理QrCodeEntityVo对象列表,将图片URL转换为可下载的压缩包。通过设置HttpServletResponse,创建ZipOutputStream,并利用HttpURLConnection下载图片,然后将图片流写入ZIP压缩包中。QrCodeTypeEnum枚举用于定义不同类型的二维码。
摘要由CSDN通过智能技术生成

根据图片URL生成到压缩包

vo类

package com.ruoyi.common.utils.file;

import com.ruoyi.common.enums.QrCodeTypeEnum;
import lombok.Data;

@Data
public class QrCodeEntityVo {
    /**
     * 名称
     */
    private String fileName;
    /**
     * 下载地址
     */
    private String url;
    /**
     * 下载类型
     */
    private QrCodeTypeEnum downType;
}

工具类方法


    /**
     * 导出图片到压缩包
     */
    public static void batchExportQrCode(HttpServletResponse response, List<QrCodeEntityVo> list) {
    //设置二维码图片名称和下载地址
        String projectUrl = RuoYiConfig.getProjectUrl() + "/common/downloadLabelsNumberQrCode";
        List<QrCodeEntityVo> voList = list.stream().map(labels -> {
            QrCodeEntityVo vo = new QrCodeEntityVo();
            vo.setFileName(labels.getFileName());
            vo.setUrl(projectUrl + "?fileName=" + labels.getFileName() + "&module=" + labels.getDownType().name());
            return vo;
        }).collect(Collectors.toList());
        String zipFileName = "QrCode.zip";
        //响应头的设置
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);

        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipOutputStream.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
        } catch (Exception e) {
            e.printStackTrace();
        }

        DataOutputStream os = null;
        for (QrCodeEntityVo vo : voList) {
            if (StringUtils.isEmpty(vo.getUrl())) {
                continue;
            }
            String fileName = vo.getFileName();
            File file = new File("");
            try {
                URL url = new URL(vo.getUrl());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                InputStream is = conn.getInputStream();
                file = FileUtils.inputStreamToFile(is, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.exists()) {
                try {
                    assert zipOutputStream != null;
                    zipOutputStream.putNextEntry(new ZipEntry(fileName));
                    os = new DataOutputStream(zipOutputStream);
                    InputStream is = new FileInputStream(file);
                    byte[] b = new byte[100];
                    int length = 0;
                    while ((length = is.read(b)) != -1) {
                        os.write(b, 0, length);
                    }
                    is.close();
                    zipOutputStream.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * InputStream 转file
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception {
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

枚举类

package com.ruoyi.common.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public enum QrCodeTypeEnum {
    /**
     * 类型1
     */
    NmCollectingLabelsQrCode,
    /**
     * 类型2
     */
    RegistrationNumberQrCode,
    ;
}

您可以使用Java的IO流来下载图片并保存到指定的文件夹中。以下是一个简单的示例代码: ```java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; public class ImageDownloader { public static void downloadImage(String imageUrl, String savePath) throws IOException { URL url = new URL(imageUrl); URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(savePath)); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.close(); in.close(); } public static void main(String[] args) throws IOException { String imageUrl = "http://example.com/image.jpg"; String savePath = "/path/to/save/image.jpg"; downloadImage(imageUrl, savePath); } } ``` 您可以将上述代码中的`imageUrl`替换为您要下载图片URL,将`savePath`替换为您要保存图片的文件路径。如果您需要将多个图片压缩成一个压缩包,可以使用Java的ZipOutputStream类来实现。以下是示例代码: ```java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ImageDownloader { public static void downloadImage(String imageUrl, String savePath) throws IOException { URL url = new URL(imageUrl); URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(savePath)); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.close(); in.close(); } public static void compressImagesToZip(String[] imageUrls, String zipFilePath) throws IOException { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath))); byte[] buf = new byte[1024]; for (int i = 0; i < imageUrls.length; i++) { String imageUrl = imageUrls[i]; String fileName = "image" + i + ".jpg"; ZipEntry entry = new ZipEntry(fileName); out.putNextEntry(entry); BufferedInputStream in = new BufferedInputStream(new URL(imageUrl).openStream()); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.closeEntry(); } out.close(); } public static void main(String[] args) throws IOException { String[] imageUrls = {"http://example.com/image1.jpg", "http://example.com/image2.jpg"}; String zipFilePath = "/path/to/save/images.zip"; compressImagesToZip(imageUrls, zipFilePath); } } ``` 您可以将上述代码中的`imageUrls`替换为您要下载压缩图片URL数组,将`zipFilePath`替换为您要保存压缩包的文件路径。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值