阿里云Bucket的简单使用
准备工作
- 创建Bucket
- 标准存储
- 在RAM访问控制中创建用户
- 保存AccessKey ID 和 AccessKey Secret (重要,bucket创建完成后才能显示且仅此一次)
- 设置权限 AliyunOSSFullAccess
java实现用户头像的上传
-
依赖引入
<!-- OSS--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
-
application.yml配置
#----------阿里云OSS配置-------------- aliyun: oss: endpoint: [Endpoint(地域节点)——外网访问] access-key-id: [AccessKey ID] access-key-secret: [AccessKey Secret] bucketname: [bucketName]
-
OSSConfig配置类
@ConfigurationProperties(prefix = "aliyun.oss") @Configuration @Data public class OSSConfig { private String endpoint; private String accessKeyId; private String accessKeySecret; private String bucketname; }
-
上传接口Controller
@RestController @RequestMapping("/api/user_img") public class AccountController { @Autowired private FileService fileService; /** * 文件上传 最大1M * @param file * @return */ @PostMapping("upload") public JsonData uploadUserImg(@RequestPart("file")MultipartFile file){ String result = fileService.uploadUserImg(file); return result!=null ? JsonData.buildSuccess(result):JsonData.buildResult("用户头像文件上传失败"); } }
-
上传方法实现
public interface FileService { String uploadUserImg(MultipartFile file); } @Service @Slf4j public class FileServiceImpl implements FileService { @Autowired private OSSConfig ossConfig; @Override public String uploadUserImg(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); //获取文件原始名称 xxx.jpg String originalFilename = file.getOriginalFilename(); //jdk8语法日期格式 LocalDateTime ldt = LocalDateTime.now(); DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy/MM/dd"); // user/2023/07/18/asdwad String folder = pattern.format(ldt); String fileName = CommonUtil.generateUUID(); String extendsion = originalFilename.substring(originalFilename.lastIndexOf(".")); //在oss上的bucket 创建文件夹 String newFileName = "user/"+folder+"/"+fileName+extendsion; try { PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileName, file.getInputStream()); //拼装返回路径 if(putObjectResult!=null){ String imgUrl = "https://"+bucketname+"."+endpoint+"/"+newFileName; return imgUrl; } } catch (IOException e) { log.info("文件上传失败"); }finally { ossClient.shutdown(); } return null; } }