欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-27 08:36:44
...

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的原因,所以对两位博主的代码进行了合并!

最终实现如下图:
Https图片链接批量打包下载zip

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