java 通过 url 直接下载 zip 压缩包

前言

最近项目中,需要多个文件打包下载,这里通过将多个 url 文件直接转为一个 zip 压缩包下载的方式

实现

package com.pip.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 下载zip工具类
 * @author: ChengQichuan
 * @email: fushengyicheng@qq.com
 * @time: 2021/8/9 13:51
 */
public class ZipUtil {

    private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    /**
     * 生成Zip文件
     */
    public static void generateZipFile(HttpServletResponse response, List<String> fileUrl, String fileName) throws IOException {

        ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());

        for (int i = 0; i < fileUrl.size(); i++) {

            String url = fileUrl.get(i);
            String[] urlSpit = url.split("\\.");
            String postfix = urlSpit[urlSpit.length - 1];

            zipOut.putNextEntry(new ZipEntry(System.currentTimeMillis() + "." + postfix));

            InputStream stream = ZipUtil.getInputStreamByUrl(fileUrl.get(i));

            if (null == stream) {
                continue;
            }

            int temp = 0;
            while ((temp = stream.read()) != -1) {
                zipOut.write(temp);
            }
            stream.close();
        }

        zipOut.closeEntry();
        zipOut.close();
    }

    /**
     * 通过url读取图片信息
     */
    public static InputStream getInputStreamByUrl(String url) {

        InputStream ins = null;

        try {

            URL url_ = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url_.openConnection();
            conn.setConnectTimeout(3 * 1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            ins = conn.getInputStream();

        } catch (IOException e) {
            logger.info("图片读取失败!-->" + e);
        }

        return ins;
    }

    /**
     * 导出Zip文件
     */
    public static void exportZipFile(String fileName, List<String> fileUrl, HttpServletResponse response, HttpServletRequest request) {

        try {

            // 浏览器处理乱码问题
            String userAgent = request.getHeader("User-Agent");

            // filename.getBytes("UTF-8")处理safari的乱码问题
            byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");

            // 各浏览器基本都支持ISO编码
//            fileName = new String(bytes, "ISO-8859-1");
            fileName = URLEncoder.encode(fileName, "utf-8");

            // 文件名外的双引号处理firefox的空格截断问题
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            ZipUtil.generateZipFile(response, fileUrl, fileName);

        } catch (Exception e) {
            logger.info("下载失败!-->" + e);
        }
    }



    /**
     * 导出普通文件
     */
    public static void exportFile(String fileName, String fileUrl, HttpServletResponse response, HttpServletRequest request) {

        try {

            // 浏览器处理乱码问题
            String userAgent = request.getHeader("User-Agent");

            // filename.getBytes("UTF-8")处理safari的乱码问题
            byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");

            // 各浏览器基本都支持ISO编码
//            fileName = new String(bytes, "ISO-8859-1");
//            fileName = new String(bytes, "iso8859-1");
            fileName = URLEncoder.encode(fileName, "utf-8");


            // 文件名外的双引号处理firefox的空格截断问题
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);


            OutputStream os = response.getOutputStream();
            byte[] data = LocalHttpClient.get(fileUrl);
            os.write(data);
            os.flush();
            os.close();

        } catch (Exception e) {
            logger.info("下载失败!-->" + e);
        }
    }

}

/**
 * url获取字节数据
 * @author: ChengQichuan
 * @email: fushengyicheng@qq.com
 * @time: 2021/8/9 13:56
 */
public class LocalHttpClient {

    public static byte[] get(String url) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpUriRequest httpUriRequest = RequestBuilder.get().setUri(url).build();
        return httpclient.execute(httpUriRequest, new AbstractResponseHandler<byte[]>() {
            @Override
            public byte[] handleEntity(HttpEntity entity) throws IOException {
                return EntityUtils.toByteArray(entity);
            }
        }, HttpClientContext.create());
    }

}

相关文章

转载请注明: 转载自 浮生一程
本文链接地址 java 通过 url 直接下载 zip 压缩包
上一篇
下一篇