目录
🧂1.OSS开通
🌭2.头像上传整合OSS
🚍2.1.引入依赖
🚍2.2添加配置
🚍2.3创建配置类
🚍2.4添加实现类
🚍2.5controller调用接口
🚍2.6postman测试
1.OSS开通
- 1.登录阿里云,搜索oss
- 2.创建bucket
RAM权限:
- 阿里云用于各个产品的权限,基于RBAC模型,进行简单管理账号、统一分配权限、集中管控资源,从而建立安全、完善的资源控制体系。
- 众多产品,一般采用子账号进行分配权限,防止越权攻击
- 3.创建用户,为其分配权限
- 4.确定之后发送验证码
- 5.获取AccessKey ID ,AccessKey Secret;只出现一次,务必粘贴复制
- 6. 按需添加权限
2.头像上传整合OSS
官方参考文档:OSS官网手册
2.1.引入依赖
<!--阿里云OSS--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version></dependency>
2.2添加配置
yml文件没有提示,不要考虑是不是错了
#阿里云OSS
aliyun:oss:#地域节点endpoint: access-key-id: access-key-Secret: bucket-name: hqdmdxz-user
2.3创建配置类
创建配置类,获取yml中的文件配置,注意@Value注解的使用
@Data
@Configuration
public class OssConfig {@Value("${aliyun.oss.endpoint}")private String endpoint;@Value("${aliyun.oss.access-key-id}")private String accessKeyId;@Value("${aliyun.oss.access-key-Secret}")private String accessKeySecret;@Value("${aliyun.oss.bucket-name}")private String bucketName;
}
2.4添加实现类
- 先上传文件,返回url地址,再和普通表单一并提交(推荐这种,更加灵活,失败率低)
- 文件和普通表单一并提交(设计流程比较多,容易超时和失败)
注意:默认SpringBoot最大文件上传是1M,大家测试的时候注意一下
@Slf4j
@Service
public class FileServiceImpl implements FileService {@Autowiredprivate OssConfig ossConfig;/*** 上传头像** @param file* @return*/@Overridepublic String uploadUserImage(MultipartFile file) {//1.获取相关配置String bucketName = ossConfig.getBucketName();String endpoint = ossConfig.getEndpoint();String accessKeyId = ossConfig.getAccessKeyId();String accessKeySecret = ossConfig.getAccessKeySecret();//2.创建oss对象OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);//3.获取原始文件名String originalFilename = file.getOriginalFilename();//4.获取当前时间LocalDateTime nowTime = LocalDateTime.now();//5.格式化的模板DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");//6.将当前日期格式化String formatTime = dateTimeFormatter.format(nowTime);//7.获取uuidString uuid = CommonUtil.generateUUID();//8.获取文件后缀.jpgString extension = originalFilename.substring(originalFilename.lastIndexOf("."));//9.拼装路径oos存储路径 user/2024/03/22/2131241215.jpgString fileName = "user/" + formatTime + "/" + uuid + extension;try {//10.上传到ossPutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, file.getInputStream());//11.返回拼装路径if (putObjectResult != null) {String imageUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;return imageUrl;}} catch (IOException e) {log.error("文件上传失败:{}", e);} finally {//oss关闭,避免内存泄露ossClient.shutdown();}return null;}
}
2.5controller调用接口
上传文件,调用接口实现类,返回图片地址
@Autowiredprivate FileService fileService;/*** 上传头像** @return*/@ApiOperation("头像上传")@PostMapping("/upload")public JsonData uploadUserImage(@ApiParam(value = "文件上传", required = true)@RequestPart("file") MultipartFile file) {String imageUrl = fileService.uploadUserImage(file);if (imageUrl != null) {return JsonData.buildSuccess(imageUrl);}return JsonData.buildResult(CodeEnum.FILE_UPLOAD_USER_IMAGE_ERROR);}