这里封装了一个ZipUtil工具类,每个项目用到的OSS服务可能不一样,但是SDK都大差不差,只需要替换掉里面获取文件流的方法就可以了
/**
* 文件打包下载
*
* @author zzt
* @version v1.0.0
* @date 2023/6/14 15:01
*/
@Slf4j
@Component
public class ZipUtils {
private static OssClient ossClient;
public ZipUtils(OssClient ossClient) {
ZipUtils.ossClient = ossClient;
}
/**
* 获取多个文件压缩下载
*
* @param zipFileName:压缩文件名称
*/
@SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"})
public static void downloadZip(@NotNull List<FileVo> fileList, @NotBlank String zipFileName) {
//获取resources文件夹的真实路径
String path = ZipUtils.class.getClassLoader().getResource("temporary").getPath();
String destFilePath = path + "/" + zipFileName + ".zip";
File zipFile = new File(destFilePath);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
byte[] buf = new byte[1024 * 4];
for (FileVo fileVo : fileList) {
//替换自己项目中的OSS方法 InputStream inputStream = ossClient.downloadFile(fileVo.getFileKey());
zos.putNextEntry(new ZipEntry(fileVo.getFileName()));
int len;
while ((len = inputStream.read(buf)) != -1) {
zos.write(buf, 0, len);
}
}
} catch (Exception e) {
log.error("FileUtils.downloadZip()压缩文件报错,报错原因:[{}]", e.getMessage(), e);
throw new RuntimeException("压缩文件失败!");
}
//下载文件
ZipUtils.downloadFile(destFilePath);
if (zipFile.exists()) {
zipFile.delete();
}
}
/**
* 下载模工具(resources下文件)
*
* @param filePath zip文件路径
*/
@SuppressWarnings("ConstantConditions")
public static void downloadFile(String filePath) {
//获取response
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
//读取文件
try (FileInputStream resourceAsStream = new FileInputStream(filePath);
BufferedInputStream fis = new BufferedInputStream(resourceAsStream);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
//获取文件名
String name = URLEncoder.encode(FileUtil.getName(filePath), "UTF-8").replaceAll("\\+", "%20");
int available = fis.available();
byte[] buffer = new byte[1024 * 4];
int r;
while (-1 != (r = fis.read(buffer))) {
toClient.write(buffer, 0, r);
}
response.setHeader("Content-Disposition", "attachment;filename=" + name);
response.addHeader("Content-Length", "" + available);
response.setContentType("application/octet-stream;charset=UTF-8");
toClient.flush();
} catch (Exception e) {
log.error("FileUtils.downloadTemplateFile()下载文件报错,报错原因:[{}]", e.getMessage(), e);
throw new RuntimeException("下载失败!");
}
}
}