一、导入依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.5.8</version>
</dependency>
二、配置文件
在配置文件application-dev.yml中配置minio服务地址,用户名,密码和桶名称
minio:
endpoint: http://172.0.0.1:9000
accessKey: minioAdmin
secretKey: minioAdmin
bucketName: bucket1
设置配置类读取minio配置信息
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "minio") //前缀
public class MinioPropertiesConfig {
/**
* 端点
*/
private String endpoint;
/**
* 用户名
*/
private String accessKey;
/**
* 密码
*/
private String secretKey;
/**
* 桶名称
*/
private String bucketName;
}
三、测试类中实现文件的上传、并且返回文件的保存路径
package com.atguigu.spzx.manager.service.impl;
import cn.hutool.core.date.DateUtil;
import com.atguigu.spzx.manager.properties.MinioProperties;
import com.atguigu.spzx.manager.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.UUID;
@Service
public class FileUploadServiceImpl implements FileUploadService {
@Autowired
private MinioProperties minioProperties ;
@Override
public String fileUpload(MultipartFile multipartFile) {
try {
// 创建一个Minio的客户端对象
MinioClient minioClient = MinioClient.builder()
.endpoint(minioProperties.getEndpointUrl())
.credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
.build();
// 判断桶是否存在
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
if (!found) { // 如果不存在,那么此时就创建一个新的桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
} else { // 如果存在打印信息
System.out.println("Bucket 'bucket1' already exists.");
}
// 设置存储对象名称,
//格式为日期+uuid名称
String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
String uuid = UUID.randomUUID().toString().replace("-", "");
String fileName = dateDir+"/"+uuid+multipartFile.getOriginalFilename();
System.out.println(fileName);
//上传文件
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
.object(fileName)
.build();
minioClient.putObject(putObjectArgs) ;
//返回文件存储路径
return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}