具体sdk的使用请参考百度云BOS SDK官网
一、yml文件配置ak、sk及添加sdk依赖
bcs:
bos:
ak: 37792a864fe6*********
sk: 1dc18a5e68df*********
<!--百度云-->
<dependency>
<groupId>com.baidubce</groupId>
<artifactId>bce-java-sdk</artifactId>
<version>0.10.47</version>
</dependency>
二、sdk使用
2.1、初始化操作BOS的client以及判断存储桶是否存在的通用方法
public BosClient initCosClient(String ACCESS_KEY_ID, String SECRET_ACCESS_KEY) {
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
BosClient client = new BosClient(config);
return client;
}
public Boolean bucketExit(BosClient bosClient, String bucketName) {
boolean exists = bosClient.doesBucketExist(bucketName);
return exists;
}
2.2、获取存储桶列表
@Override
public ArrayList<String> getBCSBucket(String ACCESS_KEY_ID, String SECRET_ACCESS_KEY) {
log.info("初始化BOS客户端");
InitBosClient initBosClient = new InitBosClient();
BosClient client = initBosClient.initCosClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
List<BucketSummary> buckets = client.listBuckets().getBuckets();
ArrayList<String> bucketNames = new ArrayList<>();
for (BucketSummary bucket : buckets) {
bucketNames.add(bucket.getName());
}
log.info("bucket列表" + bucketNames);
return bucketNames;
}
2.3、文件上传
@Override
public String uploadFile(MultipartFile file, String ACCESS_KEY_ID, String SECRET_ACCESS_KEY) throws IOException {
log.info("初始化BOS客户端");
InitBosClient initBosClient = new InitBosClient();
BosClient client = initBosClient.initCosClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
InputStream inputStream = file.getInputStream();
String objectKey = file.getOriginalFilename();
try {
client.putObject(bucketName, objectKey, inputStream);
return "success";
} catch (Exception e) {
log.error(e.getLocalizedMessage());
return "false";
}
}