1. 名词初识
基本概念的文档:
https://help.aliyun.com/document_detail/87728.html?spm=a2c4g.11186623.6.572.4bf367ce3DAznc
配置环境需要了解,endpoint、accessKeyId、accessKeySecret、bucketName四个参数,即可生成ossclient
2.yml配置
# 阿里云存储参数配置
aliyun:
oss:
endpoint: xxxxxxxx
accessKeyId: Xxxxxx
accessKeySecret: xxxxxxxx
bucketName : xxxxxxxx
3.将SDK打包成工具类
@Component
public class AliyunOssUtil {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
private OSS ossClient;
private OSS getInstance() {
if(ossClient==null){
synchronized(AliyunOssUtil.class){
if(ossClient==null){
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
}
return ossClient;
}
/**
* 上传
*/
public void upload(InputStream file, String fileName){
if(Boolean.TRUE.equals(flag)){
getInstance().putObject(bucketName,fileName,file);
System.out.println("已完成上传");
}
}
public URL download(String fileName, Date expires){
return getInstance().generatePresignedUrl(bucketName,fileName, expires);
}
}
4. 总结
如果要进行二次开发要查看SDK文档,在SDK文档内部可以简单地查询自己想要的信息。
5.问题总结
5.1 没有自定义域名会出现的问题,导致url无法直接显示而是进行下载。详情和解决方案可以看
https://help.aliyun.com/knowledge_detail/39545.html
5.2 私有Object的Url无法直接进行图片服务的处理,必须在请求URL的时候构建代码如下:
String endpoint;
String accessKeyId;
String accessKeySecret;
String bucketName;
//创建oss客户端
OSS ossClient=new OSSclientBuidler().build(endpoint,accessKeyId,accessKeySecret);
//设置url请求
GeneratePresignedUrlRequest request=new GeneratePresignedUrlRequest(bucketName,fileName);
request.setExpiration(expires);
request.setMethod(HttpMethod.GET);
//这里设置处理的样式
request.setProcess(process);
//调用获得需求的url
URL url=ossClient.generatePresignedUrl(request);