1.需求背景
- C端业务用户头像上传
- 海量图片音频、视频存储
- 用户行为日志存储
(1)阿里云OSS介绍
- 对象存储OSS(Object Storage Service)是阿里云提供的海量、安全、低成本、高持久的云存储服务。其数据设计持久性不低于99.9999999999%(12个9),服务设计可用性不低于99.995%。
- OSS具有与平台无关的RESTful API接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
- 提供标准、低频访问、归档和冷归档四种存储类型,全面覆盖从热到冷的各种数据存储场景:
2.开通阿里云OSS
注意:这块secret一定要自己保存起来,后续无法查到这个值。
3.创建SpringBoot项目
(1)创建maven项目,添加maven依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>compile</scope> </dependency> </dependencies>
(2)创建主类
@SpringBootApplication public class OssApplication { public static void main(String[] args) { SpringApplication.run(OssApplication.class, args); } }
(3)创建yml配置文件
server: port: 8019 spring: application: name: oss-server
(4)启动验证
4.SpringBoot整合OSS
(1)添加oss-maven依赖
<!-- OSS依赖--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
(2)yml配置OSS信息
# 阿里云OSS配置 aliyun: oss: end-point: oss-cn-hangzhou.aliyuncs.com access-key-id: LTAI5t9w***** access-key-secret: OXK24t76***** bucket-name: oss-test-img
(3)读取yml配置,创建OSSConfig
/** * @description OSS配置类 * @author lixiang */ @ConfigurationProperties(prefix = "aliyun.oss") @Configuration @Data public class OSSConfig { private String endPoint; private String accessKeyId; private String accessKeySecret; private String bucketName; }
(4)编写FileService
public interface FileService { /** * 阿里云OSS文件上传 * @param file * @return */ String upload(MultipartFile file); }
(5)编写实现类FileServiceImpl
/** * 文件上传业务类 * * @author lixiang */ @Service @Slf4j public class FileServiceImpl implements FileService { @Autowired private OSSConfig ossConfig; /** * 阿里云OSS文件上传 * * @param file */ @Override public String upload(MultipartFile file) { //获取相关配置 String bucketName = ossConfig.getBucketName(); String endPoint = ossConfig.getEndPoint(); String accessKeyId = ossConfig.getAccessKeyId(); String accessKeySecret = ossConfig.getAccessKeySecret(); //创建OSS对象 OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret); //获取原生文件名 String originalFilename = file.getOriginalFilename(); //JDK8的日期格式 LocalDateTime time = LocalDateTime.now(); DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd"); //拼装OSS上存储的路径 String folder = dft.format(time); String fileName = generateUUID(); String extension = originalFilename.substring(originalFilename.lastIndexOf(".")); //在OSS上bucket下的文件名 String uploadFileName = "user/" + folder + "/" + fileName + extension; try { PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream()); //拼装返回路径 if (result != null) { return "https://"+bucketName+"."+endPoint+"/"+uploadFileName; } } catch (IOException e) { log.error("文件上传失败:{}",e.getMessage()); } finally { //OSS关闭服务,不然会造成OOM ossClient.shutdown(); } return null; } /** * 获取随机字符串 * @return */ private String generateUUID() { return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32); } }
(6)编写控制层
@Slf4j @RestController @RequestMapping("/file") public class FileController { @Autowired private FileService fileService; /** * 文件上传接口 * @param file * @return */ @PostMapping("/upload") public Map<String, Object> upload(@RequestPart("file") MultipartFile file){ String imgFileStr = fileService.upload(file); return buildResult(imgFileStr); } /** * 测试返回拼装,根据公司自己封装的统一返回去写 * @param str * @return */ private Map<String,Object> buildResult(String str){ Map<String, Object> result = new HashMap<>(); //判断字符串用lang3下的StringUtils去判断,这块我就不引入新的依赖了 if(str== null || "".equals(str)){ result.put("code",10000); result.put("msg","图片上传失败"); result.put("data",null); }else{ result.put("code",200); result.put("msg","图片上传成功"); result.put("data",str); } return result; } }
(7)测试文件上传