1.添加pom依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.5.4</version>
</dependency>
2.配置文件的endpoint
minio:
endpoint: http://192.168.1.10:9000
accessKey: TaYE5BOHlkOqso0ut6OC
secretKey: Ex9OgtlL3yn3VaTyQKST6GccDmfNYqIc4wNgNFt1
bucketName: 2002
3.添加MinioProperties类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "minio")
@Data
public class MinioProperties {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
}
4.添加MinioUtil 类
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.mai.exception.GlobalException;
import com.mai.exception.ServiceException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
@Data
@AllArgsConstructor
@Slf4j
public class MinioUtil {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
public String upload(MultipartFile file){
MinioClient minioClient = new MinioClient.Builder()
.endpoint(endpoint)
.credentials(accessKey,secretKey)
.build();
String url = null;
try {
String fileName = file.getOriginalFilename();
String substring = fileName.substring(fileName.lastIndexOf("."));
String objectName = UUID.randomUUID().toString() + substring;
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(file.getInputStream(),file.getSize(),-1)
.contentType(file.getContentType())
.build());
url = endpoint + "/" + bucketName + "/" + objectName;
} catch (Exception e) {
throw new ServiceException("401","图片上传失败");
}
return url;
}
/**
* @author gaojun
* @desc 删除文件
* 文档链接 https://help.aliyun.com/document_detail/84842.html?spm=a2c4g.11186623.6.770.4f9474b4UYlCtr
* @email 15037584397@163.com
*/
public void delete(String objectName) {
try {
MinioClient minioClient = new MinioClient.Builder()
.endpoint(endpoint)
.credentials(accessKey,secretKey)
.build();
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
throw new ServiceException("401","图片删除失败");
}
}
}
5.添加配置类
package com.mai.config;
import com.mai.comman.MinioProperties;
import com.mai.util.MinioUtil;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@Slf4j
public class MinioConfiguration {
@Bean
@ConditionalOnMissingBean
public MinioUtil minioUtil(MinioProperties minioProperties){
return new MinioUtil(minioProperties.getEndpoint(),
minioProperties.getAccessKey(),
minioProperties.getSecretKey(),
minioProperties.getBucketName());
}
}
6.controller调用
package com.mai.controller;
import com.mai.config.AuthAccess;
import com.mai.entity.Result;
import com.mai.util.MinioUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
@RestController
@RequestMapping("/common")
public class MinioFileController {
@Autowired
private MinioUtil minioUtil;
@AuthAccess
@PostMapping("/shangchuan")
public Result upload(MultipartFile file) throws Exception {
if(file.isEmpty()){
return Result.error("文件为空");
}
String url = minioUtil.upload(file);
return Result.success(url);
}
@AuthAccess
@DeleteMapping("/delete")
public Result delete(@RequestParam String url){
String objectName = extractObjectName(url);
minioUtil.delete(objectName);
return Result.success();
}
//获取图片url的objectName
//"http://192.168.1.10:9000/test/cbba9f4f-4ddc-451a-bbce-a1fd5798fd08.jpg"中的
//cbba9f4f-4ddc-451a-bbce-a1fd5798fd08.jpg ==> objectName
public static String extractObjectName(String url) {
url = url.replaceAll("\"", "");
int lastSlashIndex = url.lastIndexOf('/');
if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
String objectName = url.substring(lastSlashIndex + 1);
return objectName;
}
return null;
}
}
7.前端Vue实例代码
<template>
<div>
<el-table
:data="users"
style="width: 100%"
>
<el-table-column prop="strator" label="用户" width="180"> </el-table-column>
<el-table-column prop="username" label="用户名" width="180"> </el-table-column>
<el-table-column label="头像">
<template slot-scope="scope ">
<el-upload
class="avatar-uploader"
action="http://localhost:9090/common/upload"
:on-success="res => handleAvatarSuccess(res, scope.file, scope.$index)"
:before-upload="beforeAvatarUpload"
:show-file-list="false"
>
<img v-if="scope.row.avatar" :src="scope.row.avatar" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import request from '@/util/request';
export default {
name: "fistHome",
data() {
return {
users: [],
user:{}
};
},
mounted(){
this.selectAllUser()
},
methods: {
handleAvatarSuccess(res, file,index) {
console.log(res);
// console.log(file);
this.user = this.users[index];
console.log(this.user);
this.user.avatar = res.data
request.put('/user/update',this.user).then(res =>{
if(res.code === '200'){
this.$message.success('图片上传成功!')
}
})
},
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg" || file.type === "image/png";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error("上传头像图片只能是 jpg或png 格式!")
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!")
}
return isJPG && isLt2M;
},
selectAllUser(){
request.get('/user').then(res =>{
if(res.code === '200'){
this.users = res.data
}
})
}
},
};
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 60px;
height: 60px;
line-height: 60px;
text-align: center;
}
.avatar {
width: 60px;
height: 60px;
display: block;
}
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>