在 pom.xml 文件中添加依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>x.x.x</version>
</dependency>
在配置文件中添加 OSS 配置项
aliyun:
oss:
# oss对外服务的访问域名
endpoint: oss-cn-beijing.aliyuncs.com
# 访问身份验证中用到用户标识
accessKeyId: LTAI5
# 用户用于加密签名字符串和oss用来验证签名字符串的密钥
accessKeySecret: RYN
# oss的存储空间
bucketName: itwanger-oss1
# 上传文件大小(M)
maxSize: 3
# 上传文件夹路径前缀
dir:
prefix: codingmore/images/
添加配置类OssClientConfig.java
@Configuration
public class OssClientConfig {
@Value("${aliyun.oss.endpoint}")
private String endpoint ;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId ;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Bean
public OSSClient createOssClient() {
return (OSSClient)new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
上传文件API (Controller)
@RestController
@RequestMapping("/upload")
public class OssController {
@Autowired
private OssService ossService;
@PostMapping("/files")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
return ossService.upload(file);
}
}
上传文件API (Service)
@Service
public class OssService {
@Value("${aliyun.oss.maxSize}")
private int maxSize;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Value("${aliyun.oss.dir.prefix}")
private String dirPrefix;
@Autowired
private OSSClient ossClient;
public String upload(MultipartFile file) {
String objectName = getBucketName(name);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName,inputStream);
return formatPath(objectName);
}
private String getBucketName(String url){
String ext = "";
for(String extItem:imageExtension){
if(url.indexOf(extItem) != -1){
ext = extItem;
break;
}
}
return dirPrefix+ DateUtil.today()+"/"+ IdUtil.randomUUID()+ext;
}
private String formatPath(String objectName){
return "https://" +bucketName+"."+ ossClient.getEndpoint().getHost() + "/" + objectName;
}
}