下载多张图片并压缩成压缩包

版权声明:分享知识是一种快乐,愿你我都能共同成长! https://blog.csdn.net/qidasheng2012/article/details/89142737

工具类

package com.manage.util;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 图片下载工具类
 */
public class ImageDownloadUtil {

    /**
     * 下载多张图片的压缩包
     * @param request
     * @param response
     * @param imgUrlStr 多张图片URL地址逗号拼接字符串
     * @param zipName 压缩包名称
     * @throws Exception
     */
    public static void downloadImagesZip(HttpServletRequest request, HttpServletResponse response, String imgUrlStr,String zipName) throws Exception {
        downloadImagesZip(request, response, imgUrlStr.split(","), zipName);
    }

    /**
     * 下载多张图片的压缩包
     * @param request
     * @param response
     * @param imgUrlList 多张图片URL地址list集合
     * @param zipName 压缩包名称
     * @throws Exception
     */
    public static void downloadImagesZip(HttpServletRequest request, HttpServletResponse response, List imgUrlList, String zipName) throws Exception {
        Integer size = imgUrlList == null ? 10 : imgUrlList.size();
        downloadImagesZip(request, response, (String[]) imgUrlList.toArray(new String[size]), zipName);
    }

    /**
     * 下载多张图片的压缩包
     * @param request
     * @param response
     * @param imgUrls 多张图片URL地址数组
     * @param zipName 压缩包名称
     * @throws Exception
     */
    public static void downloadImagesZip(HttpServletRequest request, HttpServletResponse response, String[] imgUrls,String zipName) throws Exception {
        // 获取多张图片的二进制
        byte [] data = getImagesByte(imgUrls);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
        IOUtils.closeQuietly(response.getOutputStream());
    }


    /**
     * 获取多张图片的二进制
     * @param imgUrls 多张图片URL地址数组
     * @return
     * @throws Exception
     */
    public static byte[] getImagesByte(String[] imgUrls) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

        for (String imgUrl : imgUrls) {
            // 获取图片名称
            String imgName = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
            String imageName = imgName.substring(0,imgName.lastIndexOf("."));

            // 将当前的图片放到zip流中传出去
            downLoadImage(imgUrl, imageName, zipOutputStream);
        }

        IOUtils.closeQuietly(zipOutputStream);
        return outputStream.toByteArray();
    }

    /**
     * 将当前的图片放到zip流中传出去
     * @param imageUrl 图片URL地址
     * @param imageName 图片名称
     * @param zipOutputStream zip输出流
     */
    public static void downLoadImage(String imageUrl,String imageName,ZipOutputStream zipOutputStream) {
        String imgArray[] = {"jpg","png","gif","bmp","jpeg"};
        List suffixList = Arrays.asList(imgArray);
        String suffix = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);

        if(StringUtils.isNotBlank(imageUrl)){
            BufferedInputStream in = null;
            try {
                //校验读取到文件
                if (!suffixList.contains(suffix)) {
                    // 文件格式不对
                    throw new Exception("不是图片");
                }

                imageName += "." + suffix;

                URL url = new URL(imageUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty(
                        "Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                                + "application/x-shockwave-flash, application/xaml+xml, "
                                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                                + "application/x-ms-application, application/vnd.ms-excel, "
                                + "application/vnd.ms-powerpoint, application/msword, */*");
                conn.setRequestProperty("Accept-Language", "zh-CN");
                conn.setRequestProperty("Charset", "UTF-8");

                InputStream inStream = conn.getInputStream();
                if(inStream == null) {
                    throw new Exception("获取压缩的数据项失败! 图片名为:" + imageName);
                }else {
                    in = new BufferedInputStream(inStream);
                }

                // 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
                //ZipEntry zipEntry = new ZipEntry("图片/" + imageName);

                ZipEntry zipEntry = new ZipEntry(imageName);
                // 定位到该压缩条目位置,开始写入文件到压缩包中
                zipOutputStream.putNextEntry(zipEntry);

                byte[] bytes = new byte[1024 * 5]; // 读写缓冲区
                int read = 0;
                while ((read = in.read(bytes)) != -1) {
                    zipOutputStream.write(bytes, 0, read);
                }

                IOUtils.closeQuietly(inStream); // 关掉输入流
                IOUtils.closeQuietly(in); // 关掉缓冲输入流
                zipOutputStream.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

测试

@RequestMapping("/getImg")
public void getImg(HttpServletRequest request, HttpServletResponse response) {
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554790861898&di=d6919516aebaab4a5133439671672934&imgtype=0&src=http%3A%2F%2Fimg2.3lian.com%2F2014%2Ff4%2F158%2Fd%2F105.jpg");
    try {
        ImageDownloadUtil.downloadImagesZip(request,response,urlList,"image");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qidasheng2012/article/details/89142737