实战之oss附件批量下载,借鉴网上一些案例,但是没有达到预期效果,结合项目需求。实现远程将oss上的文件进行压缩,并提供给前端用户下载,经过测试完美实现该功能。
@PostMapping("downLoadZip")
public void downLoadZip(@RequestBody CourseDetailVo detailVo,
HttpServletResponse response,
@RequestParam(value = "customFileName", required = false, defaultValue = "default.zip") String customFileName) throws IOException {
List<AttachZipDto> objectNames = detailVo.getZipDtoList();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
for (AttachZipDto objectName : objectNames) {
String fileUrl = objectName.getFileOssUr();
String extension = TouUtil.getFileExtension(objectName.getFileOssUr());
if (fileUrl.startsWith("/")) {
fileUrl = fileUrl.substring(1);
}
try (InputStream inputStream = ossUtil.getFileInputStream(fileUrl)) {
zipOut.putNextEntry(new ZipEntry(objectName.getFileName()+"."+extension));
IOUtils.copy(inputStream, zipOut);
zipOut.closeEntry();
} catch (OSSException | IOException e) {
// 处理从 OSS 获取文件时发生的异常
throw new RuntimeException("Failed to retrieve file from OSS", e);
}
}
// 设置HTTP响应头
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(customFileName, StandardCharsets.UTF_8.toString()) + "\"");
// 将压缩文件写入HTTP响应
try (OutputStream outputStream = response.getOutputStream()) {
byteArrayOutputStream.writeTo(outputStream);
}
} catch (IOException e) {
// 处理 ZIP 创建或写入响应时的异常
throw e;
}
欢迎点赞、转发、收藏。
标签:objectName,oss,zipOut,附件,new,fileUrl,response,下载 From: https://blog.csdn.net/sccd2009/article/details/140766779