Springboot:华为云obs文件上传和删除

不讲别的,直接看代码

准备

AccessKey:访问密钥
SecretKey:访问密钥
endPoint:终端节点
bucketName:桶

1 添加maven依赖


    com.huaweicloud
    esdk-obs-java
    3.19.7

2 添加obs的配置信息

# huawei ods
huawei.obs.ak=hajkfhdsajkhjdkahsfjs
huawei.obs.sk=hjaksjfhdakdfhajkfhdsajkhjdkahsfjsadhaljkhdfsd
# 上传的endPoint
huawei.obs.upload.endPoint=endPoint.com
# 访问的endPoint
huawei.obs.access.endPoint=https://endPoint.com
# 桶
huawei.obs.bucketName=obs-bucket-dev

3 配置obs

import com.obs.services.ObsClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ObsConfig {

    @Value("${huawei.obs.ak}")
    private String ak;

    @Value("${huawei.obs.sk}")
    private String sk;

    @Value("${huawei.obs.upload.endPoint}")
    private String endPoint;

    @Bean
    public ObsClient getObsClient(){
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        return obsClient;
    }
}

4 创建obs工具类,提供上传和删除功能

import com.obs.services.ObsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Component
public class ObsUtil {

    @Autowired
    private ObsClient obsClient;

    @Value("${huawei.obs.bucketName}")
    private String bucketName;

    //上传文件,multipartFile就是你要的文件,
    //objectKey就是文件名,如果桶中有文件夹的话,如往test文件上传test.txt文件,那么objectKey就是test/test.txt
    public void uploadFile(MultipartFile multipartFile, String objectKey) throws Exception{
        InputStream inputStream = multipartFile.getInputStream();
        obsClient.putObject(bucketName, objectKey, inputStream);
        inputStream.close();
        obsClient.close();
    }
    public void deleteFile(String objectKey) throws Exception{
        obsClient.deleteObject(bucketName, objectKey);
        obsClient.close();
    }
}

效果展示

Springboot:华为云obs文件上传和删除_第1张图片

你可能感兴趣的:(springboot,spring,boot,华为)