OSS (Object Storage Service) 对象存储服务
引入阿里云核心依赖
<!--阿里云oss存储API-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
1、创建bucket
2、构建文件流为输入流
3、构建文件路径和文件名(包括后缀名)
4、调用 OS客户端 的上传 api 给如上参数,
5、关闭OS 客户端
采用自动装配的原理,对api进行封装为模板工具类
对象存储属性类
(该类的属性值是从配置文件application.yml中指定常量获取的)
@Data
@ConfigurationProperties(prefix = "tanhua.oss")
public class OssProperties {
private String accessKey;
private String secret;
private String bucketName;
private String url; //域名
private String endpoint;
}
模板类
public class OssTemplate {
private OssProperties ossProperties;
public OssTemplate(OssProperties ossProperties) {
this.ossProperties = ossProperties;
}
public String upload(String filename, InputStream is) {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = ossProperties.getEndpoint();
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = ossProperties.getAccessKey();
String accessKeySecret = ossProperties.getSecret();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String storePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
System.out.println(storePath);
// 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
ossClient.putObject(ossProperties.getBucketName(), storePath, is);
String url = ossProperties.getUrl() + storePath;
// 关闭OSSClient。
ossClient.shutdown();
return url;
}
bean 声明类
@EnableConfigurationProperties({
SmsProperties.class,
OssProperties.class
})
public class TanhuaAutoConfiguration {
@Bean
public SmsTemplate smsTemplate(SmsProperties properties) {
return new SmsTemplate(properties);
}
@Bean
public OssTemplate ossTemplate(OssProperties properties) {
return new OssTemplate(properties);
}
}
在 resource 目录下创建文件夹 META-INF,并创建 spring.factories文件,在其中配置自动装配的类路径全限定名
在使用时,引用该依赖,就可以直接通过对象自动注入OssTemplate 的对象,来使用他提供的相关pai