最近遇到一个功能要求从阿里云OSS服务器下载文件并批量导出,从网上找到的文章内容与现在阿里云文档操作手册有部分出入,导致拿取文件出问题,综合了大部分文章才完成功能,所以想记录一下以免下次用的时候忘记了
首先就是工具类中要连接OSS的Client
参考的文章如下:
前端批量下载请求报错处理
对返回的zip流以及blob格式的res处理
后端借鉴文章
阿里云OSS流式下载操作手册
插入maven依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
这里我的配置信息是放在配置文件中的,看项目情况 也可以放到Nacos或者数据库里
oss.host: https://oss-cn-beijing.aliyuncs.com(阿里云域名)
oss.bucketName: tests-xxxxxxx-----(oss创建的服务名)
oss.endpoint: oss-cn-beijing.aliyuncs.com(阿里云域名)
oss.accessKeyId: LTAxxxxxxxxxxxxxxxxx(这里的ID和Secret需要在阿里云的RAM)
oss.accessKeySecret: 1QInP3xxxxxxxxxxxxxxxxxxx
访问控制里创建一个你自己的用户,生成自己的秘钥对,如下图
@Data
@Component
public class OssUtil {
//读取OSS服务配置信息
private String host = AppConfig.getProperty("oss.host");
private String endpoint = AppConfig.getProperty("oss.endpoint");
private String accessKeyId = AppConfig.getProperty("oss.accessKeyId");
private String accessKeySecret = AppConfig.getProperty("oss.accessKeySecret");
private String bucketName = AppConfig.getProperty("oss.bucketName");
/**
* 上传文件
* @param file
* @return
*/
public HashMap<String, Object> upload(MultipartFile file,String path) {
if (file.isEmpty()) {
throw new ServiceException("上传文件不能为空");
}
if (!checkFileSize(file.getSize(), BaseConstant.LEN, BaseConstant.UNIT_M)) {
throw new ServiceException("上传文件大小不能超过10M");
}
HashMap<String, Object> resultMap = new HashMap<>();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
// 保存路径,注意:这里不要以 / 或 \ 开头
path += "/"+new SimpleDateFormat("yyyyMMdd").format(new Date());
String originalFilename = file.getOriginalFilename();
String uuidName = UUID.randomUUID().toString().replace("-", "");
String fileName = path + "/" + uuidName + originalFilename.substring(originalFilename.lastIndexOf("."));
resultMap.put("path",path);
resultMap.put("fileName",uuidName+originalFilename.substring(originalFilename.lastIndexOf(".")));
try {
ossClient.putObject(bucketName, fileName, file.getInputStream());
} catch (IOException e) {
throw new ServiceException("上传失败" + e.getMessage());
}