minio的部署和idea的配置可看这篇文章
芋道 Spring Boot 对象存储 MinIO 入门 | 芋道源码 —— 纯源码解析博客
在基本的后端上传逻辑之下,增加了前端的返回值:
后端代码如下:
@PostMapping("/upload")
public JSONObject upload(@RequestParam("file") MultipartFile file) throws Exception {
// 上传
String path = UUID.randomUUID().toString() ; // 文件名,使用 UUID 随机
String res = null;
try {
// 检查'my-bucketname'是否存在。
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
if (found) {
System.out.println("mybucket exists");
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucket) // 存储桶
.object(path) // 文件名
.stream(file.getInputStream(), file.getSize(), -1) // 文件内容
.contentType(file.getContentType()) // 文件类型
.build());
} else {
System.out.println("mybucket does not exist");
}
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
}
res = String.format("%s/%s/%s", endpoint, bucket, path);
System.out.println(res);
JSONObject result = new JSONObject();
result.put("path", res);
// if (!res.isEmpty())
return CommonUtil.successJson(result);
// else
// return CommonUtil.errorJson("上传失败");
}
返回给前端的是拼接好的http链接,前端采用的是upload的方式获取并展示,里面有一个重要的点就是action接口要写对,否则会产生跨域错误,在正常的接口前面加一层api,before-upload是定义上传时文件的类型,文件大小等,http-request是一个自定义上传函数,可以在JS中获取后端的返回值,content是定义上传类型,因为前端是直接返回图片,所以要将show-file-list的值设为false
HTML中的代码
<el-upload action="/api/xxx/upload" :show-file-list="showFileList"
:before-upload="beforeUpload" :http-request="uploadSectionFile"
content="multipart/form-data">
<el-button class="edit_btn" style="border: none; ">
<div>
<div class="testStyle">打开文件</div>
</div>
</el-button>
</el-upload>
<img :src=imgSrc><!-- 单页展示图片 -->
JS中的代码:
data中添加如下
showFileList: false,//控制上传显示出现的列表
imgSrc: '',//图片显示URL
methods中的函数:
uploadSectionFile(param) {
//打开文件显示文件
var fileObj = param.file;
var form = new FormData();
// 文件对象
form.append("file", fileObj);
this.api({
url: "/xxxr/upload",
method: "post",
data: form
}).then((data) => {
this.imgSrc = data.path;
})
},
beforeUpload(file) {
//上传前对文件的控制
const isJPG = file.type === 'image/png';//限制上传类型(类型里面没有ofd)
const isLt2M = file.size / 1024 / 1024;//限制上传文件大小
},
上传图片格式文件即可前端动态展示。
逻辑可能还存在不足之处,日后改进。
若大佬有直接前端点击文件后端处理返回前端展示,不经过minio的方式还请赐教。