开发环境说明:JDK 17 + SpringBoot 2.7.12
一、导入相关SKD坐标
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.13.0</version>
</dependency>
二、获取AccessKey和Secret
获取地址:ram.console.aliyun.com/manage/ak
三、文件上传代码实现
@RestController
@RequestMapping("/file")
public class UploadController {
// 地域 填写自己的
private static final String endpoint = "";
// key 填写自己的
private static final String accessKeyId = "";
// secret 填写自己的
private static final String accessKeySecret = "";
// bucket 填写自己的
private static final String bucketName = "";
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new RuntimeException("文件不能为空!");
}
// 校验文件上传类型,根据需求自定义
List<String> list = List.of(".jpg", ".png");
String filename = file.getOriginalFilename();
String type = filename.substring(filename.lastIndexOf('.'));
if (!list.contains(type)) {
throw new RuntimeException("文件类型错误!");
}
// note-img/ 是bucket下文件夹的名称
String objectName = "note-img/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssS")) + type;
OSS ossClient = new OSSClientBuilder()
.build("https://" + endpoint, accessKeyId, accessKeySecret);
try {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
ossClient.putObject(putObjectRequest);
// 返回上传结果 也就是图片的访问地址
return "https://" + bucketName + "." + endpoint + "/" + objectName;
} catch (IOException e) {
throw new RuntimeException("图片上传失败:" + e.getMessage());
} finally {
ossClient.shutdown();
}
}
}