Java整合多个文件为Zip文件,并下载

代码:

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.servlet.ServletUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public void downloadZipFile(HttpServletResponse response) throws UnsupportedEncodingException {
    //下载文件的地址
    String downLoadFilePath = "H:\\data\\downLoad\\客户跟进记录附件";

    File downLoadFilePathFile = new File(downLoadFilePath);
    //创建下载文件的的目录
    if(downLoadFilePathFile.exists()){
        FileUtil.del(downLoadFilePathFile);
    }else {
        FileUtil.mkdir(downLoadFilePathFile);
    }

    //设置需要下载的文件
    String filePath1 = "H:\\data\\upload\\20230824\\1694540372430163968-输赢报告.docx";
    String filePath2 = "H:\\data\\upload\\20230824\\1694540430982647808-客户访谈报告.docx";
    String filePath3 = "H:\\data\\upload\\20230824\\1694540430999425024-图片.png";

    File file1 = new File(filePath1);
    File file2 = new File(filePath2);
    File file3 = new File(filePath3);

    //将需要下载的文件拷贝到指定目录下
    File dstFile1 = new File(downLoadFilePath, file1.getName());
    FileUtil.copy(file1, dstFile1, true);
    File dstFile2 = new File(downLoadFilePath, file1.getName());
    FileUtil.copy(file2, dstFile2, true);
    File dstFile3 = new File(downLoadFilePath, file1.getName());
    FileUtil.copy(file3, dstFile3, true);

    String downLoadZipFilePath = downLoadFilePath+".zip";
    File downLoadZipFile = new File(downLoadZipFilePath);
    if(downLoadZipFile.exists()){
        FileUtil.del(downLoadZipFile);
    }
    
    // 生成pdf压缩包
    ZipUtil.zip(downLoadZipFilePath, downLoadFilePath, false);

    //下载压缩包
    String downloadFileName = FileUtil.getName(downLoadZipFilePath);
    downLoadZipFile = new File(downLoadZipFilePath);
    if(downLoadZipFile.exists()){
        // 写入response
        String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(downloadFileName), "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(downloadFileName, "utf-8"));
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        ServletUtil.write(response, downloadFile);
    }

}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值