JAVA实现Https图片链接批量打包下载zip

JAVA实现Https图片链接批量打包成zip下载

需求说明,将多张(https链接)图片打包成一个压缩文件然后进行下载;
import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

 /**
     * 批量下载图片后台逻辑
     * @return
     */
    @RequestMapping("/downLoadImgs")
    public void downLoadImgs(SearchParamOrder param, HttpServletRequest request, HttpServletResponse response) {
    	// 数据库取要下载图片的路径集合  
        List<OrderInfoExtend> list = orderInfoService.selectListByParam(param);

        //1.拿到对应图片地址的url数组  构造图片链接,方便下面请求
        List<String> urls = new ArrayList<>();
        if(list != null && list.size() > 0){
			for (OrderInfoExtend orderInfoExtend : list) {
	           	 if (!StringUtils.isBlank(orderInfoExtend.getReceiptImage())){
	            	// orderInfoExtend.getReceiptImage()是数据库存的图片路径  例如 "/upload/2020/01-01/xxxx.jpg"
	            	// https域名加上路径构成图片链接
	                urls.add("https://域名"+orderInfoExtend.getReceiptImage());
	            }
        	}
		}
        //2.开始批量下载功能
        try {
            String nowTimeString = System.currentTimeMillis()+"";
            String downloadFilename = nowTimeString+".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());
            for (int i = 0; i < urls.size(); i++) {
                URL url = new URL(urls.get(i));
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                if (conn instanceof HttpsURLConnection) {
                    SSLContext sc = SSLContext.getInstance("SSL");
                    // -------------------------new OrderInfoController替换成你当前类的类名即可--------------
                    sc.init(null, new TrustManager[]{new OrderInfoController.TrustAnyTrustManager()}, new 					java.security.SecureRandom());
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());
                    // -------------------------new OrderInfoController替换成你当前类的类名即可--------------
                    ((HttpsURLConnection) conn).setHostnameVerifier(new OrderInfoController.TrustAnyHostnameVerifier());
                }
                conn.connect();
                long contentLength = conn.getContentLengthLong();//获取图片的实际长度
                InputStream inputStream = conn.getInputStream();

                zos.putNextEntry(new ZipEntry(list.get(i).getRefNo()+".png"));

                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = inputStream.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                inputStream.close();
            }
            zos.flush();
            zos.close();
        } catch (Exception e) {
            System.out.println(e);
        }

    }

private static class TrustAnyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

引用1 https://blog.csdn.net/u011935772/article/details/88546982
引用2 https://blog.csdn.net/a263295782/article/details/89195388

说明一下:第一个博主的代码能下载图片,但是没有下载路径提示,不知道是不是我写错了的原因;第二位博主的代码在本地使用localhost链接能正常下载zip,但是部署到线上或者在本地获取https链接的图片时,压缩包里面的图片大小都是0kb,我猜想应该是https的原因,所以对两位博主的代码进行了合并!

最终实现如下图:
最终实现效果

[侵删;如若有不对的地方,欢迎大佬指正]

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java实现批量下载并将文件打包ZIP格式,可以使用java.util.zip包提供的类和方法。以下是一个简单的实现示例: 首先,需要准备一个文件列表,包含要下载的文件的路径。可以通过手动指定路径,或者通过程序动态获取,具体根据需求而定。 接下来,需要使用java.util.zip包中的ZipOutputStream类和FileInputStream类来实现文件的打包。可以创建一个空的ZipOutputStream对象,并使用FileInputStream读取每个文件,然后将其添加到ZipOutputStream中。最后,关闭ZipOutputStream。 同时,还需要使用java.net包中的URL和URLConnection类来进行文件的下载。可以为每个需要下载的文件创建一个URL对象,打开URLConnection连接并获取其输入流。然后,将输入流传递给FileOutputStream,使用java.io包中的FileOutputStream类将文件下载到本地。 以下是一个简单的示例代码: import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipDownloader { public static void main(String[] args) { List<String> fileList = getListOfFiles(); // 获取文件列表,具体根据需求实现 String zipFileName = "downloadedFiles.zip"; // 设定打包后的ZIP文件名 try { FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); for (String file : fileList) { URL url = new URL(file); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); zos.putNextEntry(new ZipEntry(file)); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); } zos.closeEntry(); zos.close(); System.out.println("文件下载打包ZIP完成。"); } catch (IOException e) { e.printStackTrace(); } } } 需要注意的是,该示例只是一个简单的实现,并没有处理异常情况,如文件不存在、网络连接失败等。在实际应用中,需要对这些异常进行适当的处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值