目录
上一篇文章详细介绍了在Windows环境如何安装服务minio服务器,接下来就是最重要的一部分了,如何通过java代码实现文件相关的操作呢?今天通过SpringBoot来整合Minio示例,实现文件的上传、读取、下载、删除等操作。
windows安装教程:Windows安装Minio(超详细)-CSDN博客
创建Springboot项目
引入minio相关依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.5.6</version>
</dependency>
配置上传信息
在application.yml种添加minio配置
minio:
config:
url: http://127.0.0.1:9005 #ip地址
accessKey: admin # 账号
secretKey: admin962464 # 密码
secure: false #如果是true,则用的是https而不是http,默认值是true
bucketName: "test" # 桶的名字 相当于文件夹
编写配置文件
@Data
@Configuration
@ConfigurationProperties(prefix = "minio.config")
public class MinioConfig {
/**
* 服务地址
*/
private String url;
/**
* 用户名
*/
private String accessKey;
/**
* 密码
*/
private String secretKey;
/**
* 存储桶名称
*/
private String bucketName;
@Bean
public MinioClient getMinioClient() {
return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
}
}
编写JAVA测试类
1、文件上传
Controller
@RestController
@RequestMapping("/file")
@Tag(name = "文件管理")
public class FileController {
@Autowired
private UploadService uploadService;
@PostMapping("upload")
@Operation(summary = "上传文件")
public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
FileVO upload = uploadService.upload(file);
return new Result().ok(upload);
}
}
Service
@Slf4j
@Service
public class MinioSysFileServiceImpl implements UploadService {
// 注入minio配置文件
@Autowired
private MinioConfig minioConfig;
// 注入minio client
@Autowired
private MinioClient client;
@Override
public FileVO upload(MultipartFile file) {
FileVO fileVO = new FileVO();
try {
// 获取文件真实名称
String originalFilename = file.getOriginalFilename();
// 获取文件的扩展名 例如.jpg .doc
String extname = originalFilename.substring(originalFilename.lastIndexOf("."));
// 构建文件上传相关信息
PutObjectArgs args = PutObjectArgs.builder()
.bucket(minioConfig.getBucketName())
.object(originalFilename)
.stream(file.getInputStream(), file.getSize(), -1)
.contentType(file.getContentType())
.build();
// 将文件上传到minio服务器
client.putObject(args);
log.info("文件上传成功");
// 组装文件信息,返回前端 或者存入数据路
String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + originalFilename;
fileVO.setUrl(url);
fileVO.setSize(file.getSize());
fileVO.setFileName(originalFilename);
fileVO.setExtname(extname);
} catch (Exception e) {
throw new ServerException("文件上传异常" + e.getCause().toString());
}
return fileVO;
}
}
文件返回VO
@Data
@Schema(description = "文件信息")
public class FileVO {
@Schema(description = "文件url")
private String url;
@Schema(description = "文件名称")
private String fileName;
@Schema(description = "文件大小")
private Long size;
@Schema(description = "文件扩展名")
private String extname;
}
测试结果
ok ok ok
2、Minio工具类
@Configuration
@Slf4j
public class MinioFileUtil {
@Autowired
MinioConfig minioConfig;
@Autowired
MinioClient minioClient;
/**
* 创建桶
*
* @param bucketName 桶名称
*/
public void createBucket(String bucketName) throws Exception {
if (!StringUtils.hasLength(bucketName)) {
throw new ServerException("桶名不能为");
}
minioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
}
/**
* 创建文件夹
*
* @param bucketName 桶名
* @param folderName 文件夹名称
* @return
* @throws Exception
*/
public ObjectWriteResponse createBucketFolder(String bucketName, String folderName) throws Exception {
if (!checkBucketExist(bucketName)) {
throw new ServerException("桶不存在,无法创建文件夹");
}
if (!StringUtils.hasLength(folderName)) {
throw new RuntimeException("创建的文件夹名不能为空");
}
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.bucket(bucketName)
.object(folderName + "/")
.stream(new ByteArrayInputStream(new byte[0]), 0, 0)
.build();
ObjectWriteResponse objectWriteResponse = minioClient.putObject(putObjectArgs);
return objectWriteResponse;
}
/**
* 检查桶是否存在
*
* @param bucketName 桶名称
* @return boolean true-存在 false-不存在
*/
public boolean checkBucketExist(String bucketName) throws Exception {
if (!StringUtils.hasLength(bucketName)) {
throw new ServerException("桶名不能为空");
}
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
/**
* 删除文件
*
* @param bucketName 桶名
* @param objectName 文件所在的路径 + 文件名称 例如100000/im/750510573649620992.xlsx
* @return
*/
public Boolean deleteBucketFile(String bucketName, String objectName) {
if (!StringUtils.hasLength(bucketName) || !StringUtils.hasLength(objectName)) {
throw new ServerException("桶名或文件名不能为空");
}
try {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
return true;
} catch (Exception e) {
log.info("删除文件失败");
return false;
}
}
}
总结
以上则为简单的MinIO使用案例,其还有更多强大的功能,还包括数据加密、访问控制、版本管理等功能。官方提供的 SDK非常全面 官方文档 ,可以很轻松地在应用中完成整合。总之MinIO是一个非常强大的且可靠对象存储系统,值得信赖和推广。