百度云JAVA SDK入门系列之一:BOS对象存储

具体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";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值