代码:
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);
}
}