1.引入maven依赖
<!--OSS依赖包-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2.在YAML 或 Properties配置文件配置如下内容:
aliyun:
oss:
accessKeyId: XXXXXXX # 阿里云的accessKeyId
accessKeySecret: XXXXXXXX # accessKey 密码
endPoint: XXXXXXXX # Endpoint:在阿里云oss控制台查看自己使用的endpoint,
bucketName: XXXXXX # bucket 名称
policy:
expire: 300 # 签名有效期(S)
maxSize: 10 # 上传文件大小(M)
callback: http://localhost:8080/aliyun/oss/callback # 文件上传成功后的回调地址
dir:
prefix: xxx/images/ # 上传文件夹路径前缀
#操作oss需要的一些参数
3.Ossconfig实现类
3.1.1 需要把图片改成公共读,
ossClient.setObjectAcl(bucketName, fileName, CannedAccessControlList.PublicRead);
@Service
public class OssServiceImpl implements OssService {
@Override
public OssFileResponse uploadFile(MultipartFile file) {
String endpoint = Utils.END_POINT;
String accessKeyId = Utils.ACCESS_KEY_ID;
String accessKeySecret = Utils.ACCESS_KEY_SECRET;
String bucketName = Utils.BUCKET_NAME;
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream =file.getInputStream();
//获取文件名称
String fileName = file.getOriginalFilename();
//1 在文件名称里面添加随机唯一值
String uuid = UUID.randomUUID().toString().replaceAll("-","");
fileName=uuid+fileName;
//2 文件按照日期分类
String datePath = new DateTime().toString("yyyy/MM/dd");
//拼接
fileName = datePath+"/"+fileName;
//oss方法实现上传
//第一个参数 bucket名称
//第二个参数 上传到oss文件路径和名称 fileName
//第三个参数 上传文件输入流
ossClient.putObject(bucketName, fileName, inputStream);
ossClient.shutdown();
//把上传之后文件路径返回
//需要把上传到阿里云oss路径手动拼接出来
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
OssFileResponse response = new OssFileResponse();
response.setUrl(url);
response.setFileName(file.getOriginalFilename());
return response;
} catch (Exception e){
e.printStackTrace();
return null;
}
}
}
4.读取文件配置内容
@Component
public class Utils implements InitializingBean {
//读取配置文件内容 value注解读取属性值
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String keyId;
@Value("${aliyun.oss.accessKeySecret}")
private String keySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
//定义公开静态常量
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}