版本更新 3.0.4,适配spring boot 3.x,在spring boot 2.x中也可使用
分片上传的使用参考另一篇文章:minio分片上传文件实现
版本更新到 v1.0.1
setBucketPolicy
新封装了一个组件,是对官方minio-java sdk的一个简单封装,并提供了俩个方法,供前端直传文件使用。
源码已上传GitHub:https://github.com/kangaroo1122/minio-spring-boot-starter
目前已上传至maven中央仓库,当前最新版本:3.0.4
或查看这个地址找到最新版本:https://search.maven.org/artifact/com.kangaroohy/minio-spring-boot-starter
<dependency>
<groupId>com.kangaroohy</groupId>
<artifactId>minio-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
kangaroohy:
minio:
endpoint: http://192.168.68.128:9528
access-key: admin
secret-key: admin123
配置完成,调用封装好的方法即可
其中,getPresignedPostFormData() 方法用于获取前端 POST
formData 直传的相关凭证信息,如下:
后端接口:
@GetMapping("/oss/policy")
public RestResult<Map<String, String>> policy(@RequestParam String fileName) throws MinioException {
Map<String, String> policy = minioService.getPresignedPostFormData(bucketName, fileName);
return RestResult.ok(policy);
}
前端调用:
httpRequestHandle(param) {
let _this = this;
let file = param.file;
let data = {
fileName: file.name
}
getRequest("/oss/policy", data).then(resp => {
let {xamzalgorithm, xamzcredential, policy, xamzsignature, xamzdate, host, key} = resp.data;
let formData = new FormData();
formData.append("key", key);
formData.append("x-amz-algorithm", xamzalgorithm);
formData.append("x-amz-credential", xamzcredential);
formData.append("policy", policy);
formData.append("x-amz-signature", xamzsignature);
formData.append("x-amz-date", xamzdate);
formData.append("file", file);
httpRequest("post", host, formData).then(res => {
if (res.status === 204) {
_this.directUrl = res.headers.location;
}
})
})
}
getPresignedObjectPutUrl() 方法用于获取前端 PUT
直传的 url 信息,如下:
后端接口:
@GetMapping("/oss/uploadUrl")
public RestResult<String> uploadUrl(@RequestParam String fileName) throws MinioException {
String url = minioService.getPresignedObjectPutUrl(bucketName, fileName);
return RestResult.ok(url);
}
前端调用:
urlUploadHandle(param) {
let _this = this;
let file = param.file;
let data = {
fileName: file.name
}
getRequest("/oss/uploadUrl", data).then(resp => {
let url = resp.data;
// 发送 put 请求
let config = {'Content-Type': file.type}
httpRequest("put", url, file, config).then(res => {
if (res.status == 200) {
_this.uploadUrl = url.substring(0, url.indexOf("?"))
}
})
});
}
经过测试,getPresignedObjectPutUrl() 方式传输效率 优于 getPresignedPostFormData() 方式
这两种方式上传文件,后端充当凭证获取的角色,上传文件不经过后端,由前端直传
其余方法,按需调用
如果封装的方法不满足需求,可以注入 MinioClient minioClient
调用 minioClient 提供的原始方法进行操作
@Autowired
private MinioClient minioClient;