SpringBoot整合minio
1. 下载及安装
1.1 windows版本
目录结构
启动文件
标红的地方按实际安装地更改
@echo off
REM 声明采用UTF-8编码
chcp 65001
echo.
echo [信息] 运行MinIO文服务器。
echo.
:: 设置窗口标题
title Minio文件服务
:: 设置用户名为myname
setx MINIO_ROOT_USER minio
:: 设置密码为mypassword
setx MINIO_ROOT_PASSWORD minio123
cd %~dp0
:: 切换到minio.exe文件所在目录
cd D:\dev\minio\bin
:: 启动minio服务
minio.exe server D:\dev\minio\data --console-address ":9001" --address ":9000" > D:\dev\minio\logs\minio.log
pause
1.2 Linux版本
待更新
2. SpringBoot整合minio
2.1 依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.1</version>
<exclusions>
<exclusion>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</exclusion>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
2.2 配置文件
minio:
url: http://127.0.0.1:9000 #Minio服务所在地址
bucketName: zld #存储桶名称
accessKey: minio #访问的key
secretKey: minio123 #访问的秘钥
2.3 配置类
package com.ruoyi.minio.config;
import io.minio.MinioClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
/**
* minio服务器地址
*/
private String url;
/**
* 用户名
*/
private String accessKey;
/**
* 密码
*/
private String secretKey;
/**
* 密码
*/
private String bucketName;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(url)
.credentials(accessKey, secretKey)
.build();
}
}
2.4 工具类
package com.ruoyi.minio.util;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.minio.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.Item;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
public class MinioUtil {
@Autowired
private MinioConfig prop;
@Resource
private MinioClient minioClient;
/**
* 查看存储bucket是否存在
*
* @return boolean
*/
public Boolean bucketExists(String bucketName) {
Boolean found;
try {
found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return found;
}
/**
* 创建存储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
*
* @return Boolean
*/
public Boolean removeBucket(String bucketName) {
try {
minioClient.removeBucket(RemoveBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 获取全部bucket
*/
public List<Bucket> getAllBuckets() {
try {
List<Bucket> buckets = minioClient.listBuckets();
return buckets;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 文件上传
*
* @param file 文件
* @return Boolean
*/
public String upload(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
if (StringUtils.isBlank(originalFilename)) {
throw new RuntimeException();
}
String fileName = IdUtils.simpleUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = DateUtils.datePath() + "/" + fileName;
try {
PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(prop.getBucketName()).object(objectName)
.stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
//文件名称相同会覆盖
minioClient.putObject(objectArgs);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return objectName;
}
/**
* 文件上传
*
* @param bucketName
* @param fileName
* @param multipartFile
* @return
* @throws IOException
*/
public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws IOException {
String url = "";
MinioClient minioClient = SpringUtils.getBean(MinioClient.class);
try (InputStream inputStream = multipartFile.getInputStream()) {
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (!found) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
/**
* bucket权限-读写
*/
String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_WRITE).build());
}
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
.object(fileName)
.stream(inputStream, multipartFile.getSize(), -1)
.contentType(multipartFile.getContentType()).build()
);
//路径获取
url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).
method(Method.GET).build());
url = url.substring(0, url.indexOf('?'));
//常规访问路径获取
return url;
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
/**
* 预览图片
*
* @param fileName
* @return
*/
public String preview(String fileName) {
// 查看文件地址
GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(prop.getBucketName()).object(fileName).method(Method.GET).build();
try {
String url = minioClient.getPresignedObjectUrl(build);
return url;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 文件下载
*
* @param fileName 文件名称
* @param res response
* @return Boolean
*/
public void download(String fileName, HttpServletResponse res) {
GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(prop.getBucketName())
.object(fileName).build();
try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
byte[] buf = new byte[1024];
int len;
try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
while ((len = response.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
byte[] bytes = os.toByteArray();
res.setCharacterEncoding("utf-8");
// 设置强制下载不打开
// res.setContentType("application/force-download");
res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
try (ServletOutputStream stream = res.getOutputStream()) {
stream.write(bytes);
stream.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查看文件对象
*
* @return 存储bucket内文件对象信息
*/
public List<Item> listObjects() {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(prop.getBucketName()).build());
List<Item> items = new ArrayList<>();
try {
for (Result<Item> result : results) {
items.add(result.get());
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return items;
}
/**
* 删除
*
* @param fileName
* @return
* @throws Exception
*/
public boolean remove(String fileName) {
try {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(prop.getBucketName()).object(fileName).build());
} catch (Exception e) {
return false;
}
return true;
}
/**
* 删除文件夹及文件
*
* @param bucketName bucket名称
* @param objectName 文件或文件夹名称:以.结尾为文件,以/结尾为文件夹
* @since tarzan LIU
*/
public boolean deleteObjects(String bucketName, String objectName) {
if (StringUtils.isNotBlank(objectName)) {
if (objectName.endsWith(".") || objectName.endsWith("/")) {
Iterable<Result<Item>> list = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(true).build());
ExecutorService executorService = Executors.newFixedThreadPool(10);
list.forEach(e -> {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(e.get().objectName()).build());
} catch (ErrorResponseException ex) {
throw new RuntimeException(ex);
} catch (InsufficientDataException ex) {
throw new RuntimeException(ex);
} catch (InternalException ex) {
throw new RuntimeException(ex);
} catch (InvalidKeyException ex) {
throw new RuntimeException(ex);
} catch (InvalidResponseException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
} catch (ServerException ex) {
throw new RuntimeException(ex);
} catch (XmlParserException ex) {
throw new RuntimeException(ex);
}
}
});
});
executorService.shutdown();
return true;
}
}
return true;
}
}
2.5 测试
1. 业务层
package com.ruoyi.minio.service;
import org.springframework.web.multipart.MultipartFile;
/**
* minio服务
*/
public interface MinioService {
/**
* 文件上传
*
* @param file
* @return
*/
public String upload(MultipartFile file);
/**
* 文件上传
*
* @param file
* @return
*/
public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile);
/**
* 预览图片
* @param fileName
* @return
*/
public String preview(String fileName);
/**
* 文件删除
*
* @param fileName
* @return
*/
public boolean remove(String fileName);
/**
* 删除文件夹及文件
*
* @param bucketName bucket名称
* @param objectName 文件或文件夹名称
* @since tarzan LIU
*/
public boolean deleteObjects(String bucketName, String objectName);
/**
* 删除前几天文件夹
* @param bucketName
* @param day
* @return
*/
boolean deleteObjectsByDay(String bucketName, int day);
}
package com.ruoyi.minio.service.impl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.minio.service.MinioService;
import com.ruoyi.minio.util.MinioUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
@Service
public class MinioServiceImpl implements MinioService {
@Resource
private MinioUtil minioUtil;
/**
* 文件上传
*
* @param file
* @return
*/
@Override
public String upload(MultipartFile file) {
return minioUtil.upload(file);
}
/**
* 文件上传
*
* @param bucketName
* @param fileName
* @param multipartFile
* @return
*/
@Override
public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) {
try {
return minioUtil.uploadFile(bucketName, fileName, multipartFile);
} catch (IOException e) {
throw new ServiceException("上传失败,请联系管理员");
}
}
/**
* 预览图片
*
* @param fileName
* @return
*/
@Override
public String preview(String fileName) {
return minioUtil.preview(fileName);
}
/**
* 文件删除
*
* @param fileName
* @return
*/
@Override
public boolean remove(String fileName) {
return minioUtil.remove(fileName);
}
/**
* 删除文件夹及文件
*
* @param bucketName bucket名称
* @param objectName 文件或文件夹名称
* @since tarzan LIU
*/
@Override
public boolean deleteObjects(String bucketName, String objectName) {
return minioUtil.deleteObjects(bucketName, objectName);
}
/**
* 删除前几天文件夹
*
* @param bucketName
* @param day
* @return
*/
@Override
public boolean deleteObjectsByDay(String bucketName, int day) {
String objectName = DateUtils.getDayAgoOrAfterString(day)+"/";
return minioUtil.deleteObjects(bucketName, objectName);
}
}
2. 控制层
package com.ruoyi.web.controller.minio;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.minio.service.MinioService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* minio文件管理
*/
@RestController
@RequestMapping("/minio")
public class MinioController {
@Resource
public MinioService minioService;
@PostMapping("/upload")
public AjaxResult upload(MultipartFile file) {
String upload = minioService.upload(file);
return AjaxResult.success(upload);
}
/**
* 预览图片
*
* @param fileName
* @return
*/
@GetMapping("/preview")
public AjaxResult preview(String fileName) {
String preview = minioService.preview(fileName);
return AjaxResult.success(preview);
}
/**
* 删除文件
*
* @param fileName
* @return
*/
@GetMapping("/remove")
public AjaxResult remove(String fileName) {
return AjaxResult.success(minioService.remove(fileName));
}
/**
* 删除文件夹及文件
*
* @param bucketName bucket名称
* @param objectName 文件或文件夹名称
* @since tarzan LIU
*/
@GetMapping("/deleteObjects")
public AjaxResult deleteObjects(String bucketName, String objectName) {
return AjaxResult.success(minioService.deleteObjects(bucketName, objectName));
}
/**
* 删除文件夹及文件
*
* @param bucketName bucket名称
* @param objectName 文件或文件夹名称
* @since tarzan LIU
*/
@GetMapping("/deleteObjectsByDay")
public AjaxResult deleteObjectsByDay(String bucketName, int day) {
return AjaxResult.success(minioService.deleteObjectsByDay(bucketName, day));
}
}