新建一个properties 永远存储阿里OSS的配置文件信息
因为bucket是可读不可写的 当需要获取岛文件路径时 直接使用host字段 + 文件路径即可读取文件信息
objectname 用于存储文件
aliyun.oss.endpoint = oss-cn-beijing.aliyuncs.com
aliyun.oss.bucket = lyra-news
aliyun.oss.objectname = images/
aliyun.oss.host = test
和之前一样读取配置我二级
@PropertySource("classpath:aliOSS.properties")
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOSSResources {
private String endpoint;
private String bucket;
private String objectname;
private String host;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getObjectname() {
return objectname;
}
public void setObjectname(String objectname) {
this.objectname = objectname;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
根据API文档 写配置工具类 返回时将路径和host拼接 返回名称
@Component
public class AliOSSUtils {
@Autowired
private AliyunOSSResources aliyunOSSResources;
@Autowired
private AliyunResources aliyunResources;
public String uploadFile(InputStream fileInputStream, String uploadPathAndFileName) {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = aliyunOSSResources.getEndpoint();
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = aliyunResources.getAccessKeyId();
String accessKeySecret = aliyunResources.getAccessKeySecret();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
ossClient.putObject(aliyunOSSResources.getBucket(), uploadPathAndFileName, fileInputStream);
// 关闭OSSClient。
ossClient.shutdown();
return aliyunOSSResources.getHost() + "/" + uploadPathAndFileName;
}
}