SpringBoot图片上传工具之一:minio
一、将导入minio依赖(已安装启动)
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.0</version>
</dependency>
二、在application.yml添加相关配置
minio:
endpoint: http://127.0.0.1:9000 //路径
accesskey: minioadmin
secretKey: minioadmin
bucketName: one //桶名
三、编写配置类
@Data
@Component
// ConfigurationProperties 作用通过prefix找到配置文件中的配置信息
// 然后将prefix之后的key的值赋值给当前类对应的属性
@ConfigurationProperties(prefix = "minio") // prefix前缀
public class MinioConfiguration {
private String endpoint; //连接url
private String accesskey; //用户名
private String secretKey; //密码
@Bean
public MinioClient minioClient(){
return MinioClient.builder().endpoint(endpoint).credentials(accesskey,secretKey).build();
}
}
四、编写工具类:主要完成文件名的处理
@Data
@Component
public class MinioUtil {
@Resource
private MinioClient minioClient;
@Resource
private MinioConfiguration minioConfiguration;
// 桶名
//@Value用于获取application配置文件中指定key的值,赋值给下面的属性
@Value("${minio.bucketName}")
private String bucketName;
@Data
public class FileDetail {
private String name;
private long size;
}
/**
* description: 判断bucket是否存在,不存在则创建
* @return: void
*/
public void existBucket(String name) {
try {
boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
if (!exists) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建存储bucket
* @param bucketName 存储bucket名称
* @return Boolean
*/
public Boolean makeBucket(String bucketName) {
try {
minioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 删除存储bucket
* @param bucketName 存储bucket名称
* @return Boolean
*/
public Boolean removeBucket(String bucketName) {
try {
minioClient.removeBucket(RemoveBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* description: 上传文件
*
* @param multipartFile
* @return: java.lang.String
*/
public List<String> upload(MultipartFile[] multipartFile) {
List<String> names = new ArrayList<>(multipartFile.length);
for (MultipartFile file : multipartFile) {
String fileName = file.getOriginalFilename();
String[] split = fileName.split("\\.");
if (split.length > 1) {
fileName = UUID.randomUUID().toString() + "." + split[1];
} else {
fileName = fileName + System.currentTimeMillis();
}
InputStream in = null;
try {
in = file.getInputStream();
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.stream(in, in.available(), -1)
.contentType(file.getContentType())
.build()
);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 得到文件完整URL
fileName = minioConfiguration.getEndpoint() + "/" + bucketName + "/" + fileName;
names.add(fileName);
}
return names;
}
/**
* description: 下载文件
*
* @param fileName
* @return: org.springframework.http.ResponseEntity<byte [ ]>
*/
public ResponseEntity<byte[]> download(String fileName) {
ResponseEntity<byte[]> responseEntity = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
//封装返回值
byte[] bytes = out.toByteArray();
HttpHeaders headers = new HttpHeaders();
try {
headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
headers.setContentLength(bytes.length);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setAccessControlExposeHeaders(Arrays.asList("*"));
responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseEntity;
}
/**
* 查看文件对象
* @param bucketName 存储bucket名称
* @return 存储bucket内文件对象信息
*/
public List<FileDetail> listObjects(String bucketName) {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).build());
List<FileDetail> objectItems = new ArrayList<>();
try {
for (Result<Item> result : results) {
Item item = result.get();
FileDetail fileDetail = new FileDetail();
fileDetail.setName(item.objectName());
fileDetail.setSize(item.size());
objectItems.add(fileDetail);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return objectItems;
}
/**
* 批量删除文件对象
* @param bucketName 存储bucket名称
* @param objects 对象名称集合
*/
public void removeObjects(String bucketName, List<String> objects) {
List<DeleteObject> dos =
objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
minioClient.removeObjects(
RemoveObjectsArgs.builder()
.bucket(bucketName)
.objects(dos).build());
}
}
五、编写controller
/**
* @Author: one piece
* @Description:
* @Date: 2024/1/30 15:59
*/
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {
@Resource
private MinioUtil minioUtil;
@PostMapping("/upload")
public ResponseResult<Boolean> uploadGym(MultipartFile[] file) {
log.debug(file + "");
List<String> list = minioUtil.upload(file);
log.debug(file.toString());
return new ResponseResult(ResponseResult.SUCCESS, "success", list.get(0));// 返回文件路径
}
}
六、前端上传代码vue + elementui
HTML
<el-upload
class="avatar-uploader"
action=""
:http-request="upload"
:show-file-list="false">
<img v-if="imageUrl" :src="ruleForm.pic" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
JS
upload(param) {
const formData = new FormData()
formData.append('file', param.file)
this.$axios.post("file/upload", formData).then(res => {
this.imageUrl = res.data.data
this.ruleForm.pic = res.data.data
})
}