springboot整和阿里云oss
1、开通“对象存储OSS”服务
(1)申请阿里云账号
(2)实名认证
(3)开通“对象存储OSS”服务
(4)进入管理控制台
2、创建Bucket
选择:标准存储、公共读、不开通
3、上传默认头像
创建文件夹avatar,上传默认的用户头像
4、创建Access Key
5、创建springboot项目
编写yml
#阿里云 OSS
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI4GHMMJ9Poai7uuv2PFX3
aliyun.oss.file.keysecret=ZoY9hgIyquRkn3WtozdzPjBCggoSGY
aliyun.oss.file.bucketname=guli-edu-2020-12
aliyun.oss.file.endpoint:地域名称
aliyun.oss.file.keyid:AccessKey ID
aliyun.oss.file.keysecre: AccessKey Secret
aliyun.oss.file.bucketname:Buckets
ReadConfigUtils 类:
@Component
public class ReadConfigUtils 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;
}
}
controller:
@PostMapping("uploadingAvatar")
public R UploadingAvatar(@ApiParam(name = "file", value = "文件", required = true)
@RequestParam("file") MultipartFile file){
String fileUrl = uploadingFileService.uploadingAvatar(file);
return R.ok().data("fileUrl",fileUrl);
}
service:
@Service
public class UploadingFileServiceImpl implements UploadingFileService {
@Override
public String uploadingAvatar(MultipartFile file) {
String endpoint = ReadConfigUtils.END_POINT;
String accessKeyId = ReadConfigUtils.ACCESS_KEY_ID;
String accessKeySecret = ReadConfigUtils.ACCESS_KEY_SECRET;
String bucketName = ReadConfigUtils.BUCKET_NAME;
String uploadUrl = null;
try {
String filename = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// UUID+01.jpg
filename = uuid+filename;
String dateTimePath = new DateTime().toString("yyyy/MM/dd");
// 2020/01/01/UUID+01.jpg
filename = dateTimePath+"/"+filename;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//判断oss实例是否存在:如果不存在则创建,如果存在则获取
if (!ossClient.doesBucketExist(bucketName)) {
//创建bucket
ossClient.createBucket(bucketName);
//设置oss实例的访问权限:公共读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}
InputStream inputStream = file.getInputStream();
ossClient.putObject(bucketName, filename, inputStream);
ossClient.shutdown();
//获取上传路径
//https://guli-zc.oss-cn-beijing.aliyuncs.com/guLi/IMG_20201204_154516.jpg
uploadUrl = "http://" + bucketName + "." + endpoint + "/" + filename;
return uploadUrl;
}catch (IOException e ){
e.printStackTrace();
return null;
}
}
}