Java下载压缩包(zip)

package com.golden.crm.web.util;

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.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 下载zip工具类
 */
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++) {

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

            InputStream stream = this.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");

            // 文件名外的双引号处理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);

            this.generateZipFile(response, fileUrl, fileName);

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

}

转载于:https://my.oschina.net/u/3445245/blog/3085291

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java中实现压缩包下载,你可以使用Java的压缩库来创建压缩文件,然后将其发送到客户端进行下载。以下是一个简单的示例代码: ``` import java.io.*; import java.util.zip.*; public class ZipDownload { public static void main(String[] args) { // 设置要压缩的文件路径 String sourceFile = "/path/to/source/file"; // 设置下载文件的名称 String downloadFileName = "compressed.zip"; try { // 创建压缩文件输出流 FileOutputStream fos = new FileOutputStream(downloadFileName); ZipOutputStream zipOut = new ZipOutputStream(fos); // 创建要压缩的文件对象 File fileToZip = new File(sourceFile); // 添加要压缩的文件到压缩文件输出流 zipFile(fileToZip, fileToZip.getName(), zipOut); // 关闭压缩文件输出流 zipOut.close(); fos.close(); System.out.println("压缩完成:" + downloadFileName); } catch (IOException e) { e.printStackTrace(); } } private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException { if (fileToZip.isHidden()) { return; } if (fileToZip.isDirectory()) { if (fileName.endsWith("/")) { zipOut.putNextEntry(new ZipEntry(fileName)); zipOut.closeEntry(); } else { zipOut.putNextEntry(new ZipEntry(fileName + "/")); zipOut.closeEntry(); } File[] children = fileToZip.listFiles(); for (File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); } return; } FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileName); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } } ``` 这段代码将指定的文件压缩为一个名为 "compressed.zip" 的压缩包,并保存在当前目录中。你可以根据需要修改源文件路径、下载文件名称和保存路径等参数。运行该代码后,你将获得一个压缩包用于下载

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值