1、输入该网址 https://www.aliyun.com/ ,登录阿里云,没有登录过可以注册(可用支付宝直接扫码登录)
2、搜索OSS
3、点击对象存储OSS选项
4、开通对象存储OSS,进入管理控制台
5、创建Bucket(桶)(记录Bucket名称,后面会用到)
6、可按我这个模板选择,具体详情请参照官方文档
7、点击确定,创建成功
8、记录endpoint
9、点击AccessKey管理
10、创建AccessKey
11、记录keyid、keysecret
12、application.yml加入配置信息
server:
port: 8010
spring:
application:
name: service-oss
servlet:
multipart:
enabled: true
max-file-size: 100MB
max-request-size: 100MB
aliyun:
oss:
file:
endpoint: # 记录的endpoint
keyid: # 记录的keyid
keysecret: # 记录的keysecret
bucketname: # 创建的bucket的名称
13、测试
controller:
@PostMapping("/fileoss")
public Result uploadOssFile(MultipartFile file) {
//获取上传文件 MultipartFile(图片,文件都可以)
//返回上传到oss的路径
String url = ossService.uploadFileAvatar(file);
return Result.succ(url);
}
service:
String uploadFileAvatar(MultipartFile file);
serviceImpl:
@Override
public String uploadFileAvatar(MultipartFile file) {
String endpoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = file.getInputStream();
String fileName = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-","");
fileName = uuid+fileName;
//文件按照日期进行分类
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath+"/"+fileName;
ossClient.putObject(bucketName, fileName,inputStream);
ossClient.shutdown();
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
return url;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
工具类:
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件中的内容
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.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;
}
}
14、测试结果(Postman)
15、测试结果(OSS)
16、详情查看
17、结束