从OSS服务上批量获取文件下载,并打包zip。
@Slf4j
@Component
@RefreshScope
public class OssBootUtil {
/**
* 初始化 oss 客户端
*
* @return
*/
private static OSSClient initOSS(String endpoint, String accessKeyId, String accessKeySecret) {
if (ossClient == null) {
ossClient = new OSSClient(endpoint,
new DefaultCredentialProvider(accessKeyId, accessKeySecret),
new ClientConfiguration());
}
return ossClient;
}
/**
* @param zipName 压缩文件名称
* @param paths oss文件列表
* @return
*/
public static void getZipFromOSSByPaths(String zipName, List<String> paths) {
endPoint = "oss 路径";
accessKeyId = "key";
accessKeySecret = "秘钥";
bucketName = "桶名称";
initOSS(endPoint, accessKeyId, accessKeySecret);
FileOutputStream fos = null;
// 压缩文件输出流
ZipOutputStream zos = null;
try {
// 创建zip文件
fos = new FileOutputStream(zipName);
// 作用是为任何OutputStream产生校验和
// 第一个参数是制定产生校验和的输出流,第二个参数是指定Checksum的类型 (Adler32(较快)和CRC32两种)
CheckedOutputStream cos = new CheckedOutputStream(fos, new Adler32());
// 用于将数据压缩成zip文件格式
zos = new ZipOutputStream(cos);
OSSObject ossObject = null;
InputStream is = null;
// 循环根据路径从OSS获得对象,存入临时文件zip中
for (String path : paths) {
try {
log.info("下载文件路径 {}", path);
// 根据path 和 bucket 从OSS获取对象
ossObject = ossClient.getObject("dpxdata", path);
// 获取输出流
is = ossObject.getObjectContent();
// 将文件放入zip中,并命名不能重复
zos.putNextEntry(new ZipEntry(path));
// 向压缩文件中写数据
int len = 0;
while ((len = is.read()) != -1) {
zos.write(len);
}
} catch (Exception e) {
e.printStackTrace();
log.info("未找到文件 {}", path);
continue;
} finally {
is.close();
zos.closeEntry();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Controller
@GetMapping("/download2zip")
public void export(HttpServletRequest request, HttpServletResponse response) {
List<String> pathList = new ArrayList<>();
// https://oss域名/upload/agree/张**-《同意函》(2022-08-23)_1661246208735.pdf
pathList.add("upload/agree/张**-《同意函》(2022-08-23)_1661246208735.pdf");
String zipName = System.currentTimeMillis() + ".zip";
// 设置响应类型,以附件形式下载文件
response.reset();
response.setContentType("text/plain");
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Location", zipName);
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
OssBootUtil.getZipFromOSSByPath(zipName, pathList);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
final File tempZipFile = new File(zipName);
FileUtils.copyFile(tempZipFile, bos);
bos.close();
if (tempZipFile.exists()) {
tempZipFile.delete();
}
}