一、创建springboot,引入minio依赖:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
其它的依赖看自己需求引入
二、创建包结构
三、修改配置文件
min.io.endpoint = http://xx.xx.xx.xx:9000
min.io.accessKey = username
min.io.secretKey = password
四、编写配置类
package com.zym.minio.config;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "min.io")
public class MinIoConfig {
private String endpoint;
private String accessKey;
private String secretKey;
@Bean
public MinioClient getMinioClient() throws InvalidPortException, InvalidEndpointException {
MinioClient client = new MinioClient(endpoint,accessKey,secretKey);
return client;
}
}
五、编写测试方法
controller:
package com.zym.minio.controller;
import com.zym.minio.common.result.Result;
import com.zym.minio.common.result.ResultUtil;
import com.zym.minio.config.MinIoConfig;
import com.zym.minio.service.MinioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RequestMapping("/minio")
@RestController
@Api(tags = "文件操作接口")
public class MinioController {
@Autowired
private MinioService minioService;
@ApiOperation(value = "使用minio文件上传")
@PostMapping("/uploadFile")
public Result uploadFile(MultipartFile file, String bucketName) {
try {
if (StringUtils.isBlank(bucketName)){
return ResultUtil.sendErrorMessage("桶名称不能为空");
}
if (!minioService.bucketExists(bucketName)) {
minioService.makeBucket(bucketName);
}
String fileName = file.getOriginalFilename();
String objectName = new SimpleDateFormat("yyyy-MM-dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
+ fileName.substring(fileName.lastIndexOf("."));
minioService.putObject(bucketName, file, objectName);
System.out.println("文件格式为:"+file.getContentType());
System.out.println("文件原名称为:"+fileName);
System.out.println("文件存储的桶为:"+bucketName);
System.out.println("文件对象路径为:"+objectName);
return ResultUtil.success(minioService.getObjectUrl(bucketName, objectName));
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.sendErrorMessage("上传失败");
}
}
@ApiOperation(value = "使用minio文件删除")
@PostMapping("/deleteFile")
public Result deleteFile(String bucketName,String filePath) throws Exception {
if (!minioService.bucketExists(bucketName)){
throw new Exception("不存在该桶");
}
boolean flag = minioService.removeObject(bucketName, filePath);
if (flag){
return ResultUtil.sendSuccessMessage("删除成功");
}else{
return ResultUtil.sendErrorMessage("删除失败");
}
}
@ApiOperation(value = "使用minio文件下载")
@PostMapping("/downloadFile")
public Result downloadFile(String bucketName, String filePath, String originalName, HttpServletResponse response) throws Exception {
if (!minioService.bucketExists(bucketName)){
throw new Exception("不存在该桶");
}
minioService.downloadFile(bucketName, filePath, originalName, response);
return ResultUtil.sendSuccessMessage("下载成功");
}
}
service:
package com.zym.minio.service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
public interface MinioService {
/**
* 判断 bucket是否存在
*
* @param bucketName
* @return
*/
boolean bucketExists(String bucketName);
/**
* 创建 bucket
*
* @param bucketName
*/
void makeBucket(String bucketName);
/**
* 文件上传
*
* @param bucketName
* @param objectName
* @param filename
*/
void putObject(String bucketName, String objectName, String filename);
/**
* 文件上传
*
* @param bucketName
* @param objectName
* @param stream
*/
void putObject(String bucketName, String objectName, InputStream stream, String contentType);
/**
* 文件上传
*
* @param bucketName
* @param multipartFile
*/
void putObject(String bucketName, MultipartFile multipartFile, String filename);
/**
* 删除文件
* @param bucketName
* @param filePath
*/
boolean removeObject(String bucketName,String filePath);
/**
* 下载文件
*
* @param filePath
* @param originalName
* @param response
*/
void downloadFile(String bucketName, String filePath, String originalName, HttpServletResponse response);
/**
* 获取文件路径
* @param bucketName
* @param objectName
* @return
*/
String getObjectUrl(String bucketName,String objectName);
/**
* 以流形式获取文件
* @param bucketName
* @param objectName
* @param offset
* @return
*/
InputStream getObject(String bucketName,String objectName,long offset);
}
impl:
package com.zym.minio.service.impl;
import com.zym.minio.service.MinioService;
import com.zym.minio.util.MinIoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
@Service
public class MinioServiceImpl implements MinioService {
@Autowired
private MinIoUtils minIoUtils;
/**
* 判断 bucket是否存在
*
* @param bucketName
* @return
*/
@Override
public boolean bucketExists(String bucketName) {
return minIoUtils.bucketExists(bucketName);
}
/**
* 创建 bucket
*
* @param bucketName
*/
@Override
public void makeBucket(String bucketName) {
minIoUtils.makeBucket(bucketName);
}
/**
* 文件上传
*
* @param bucketName
* @param objectName
* @param filename
*/
@Override
public void putObject(String bucketName, String objectName, String filename) {
minIoUtils.putObject(bucketName, objectName, filename);
}
@Override
public void putObject(String bucketName, String objectName, InputStream stream, String contentType) {
minIoUtils.putObject(bucketName, objectName, stream, contentType);
}
/**
* 文件上传
*
* @param bucketName
* @param multipartFile
*/
@Override
public void putObject(String bucketName, MultipartFile multipartFile, String filename) {
minIoUtils.putObject(bucketName, multipartFile, filename);
}
/**
* 删除文件
* @param bucketName
* @param filePath
*/
@Override
public boolean removeObject(String bucketName,String filePath) {
return minIoUtils.removeObject(bucketName,filePath);
}
/**
* 下载文件
*
* @param filePath
* @param originalName
* @param response
*/
@Override
public void downloadFile(String bucketName, String filePath, String originalName, HttpServletResponse response) {
minIoUtils.downloadFile(bucketName,filePath, originalName, response);
}
/**
* 获取文件路径
* @param bucketName
* @param objectName
* @return
*/
@Override
public String getObjectUrl(String bucketName,String objectName) {
return minIoUtils.getObjectUrl(bucketName,objectName);
}
}
minioutils:
package com.zym.minio.util;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InvalidExpiresRangeException;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Component
public class MinIoUtils {
@Autowired
private MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
/**
* 检查存储桶是否存在
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean bucketExists(String bucketName) {
boolean flag = false;
flag = minioClient.bucketExists(bucketName);
if (flag) {
return true;
}
return false;
}
/**
* 创建存储桶
*
* @param bucketName 存储桶名称
*/
@SneakyThrows
public boolean makeBucket(String bucketName) {
boolean flag = bucketExists(bucketName);
if (!flag) {
minioClient.makeBucket(bucketName);
return true;
} else {
return false;
}
}
/**
* 列出所有存储桶名称
*
* @return
*/
@SneakyThrows
public List<String> listBucketNames() {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>();
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}
/**
* 列出所有存储桶
*
* @return
*/
@SneakyThrows
public List<Bucket> listBuckets() {
return minioClient.listBuckets();
}
/**
* 删除存储桶
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean removeBucket(String bucketName) {
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
// 有对象文件,则删除失败
if (item.size() > 0) {
return false;
}
}
// 删除存储桶,注意,只有存储桶为空时才能删除成功。
minioClient.removeBucket(bucketName);
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}
/**
* 列出存储桶中的所有对象名称
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public List<String> listObjectNames(String bucketName) {
List<String> listObjectNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
listObjectNames.add(item.objectName());
}
}
return listObjectNames;
}
/**
* 列出存储桶中的所有对象
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public Iterable<Result<Item>> listObjects(String bucketName) {
boolean flag = bucketExists(bucketName);
if (flag) {
return minioClient.listObjects(bucketName);
}
return null;
}
/**
* 通过文件上传到对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, String fileName) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(bucketName, objectName, fileName, null);
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 文件上传
*
* @param bucketName
* @param multipartFile
*/
@SneakyThrows
public void putObject(String bucketName, MultipartFile multipartFile, String filename) {
PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
putObjectOptions.setContentType(multipartFile.getContentType());
minioClient.putObject(bucketName, filename, multipartFile.getInputStream(), putObjectOptions);
}
/**
* 通过InputStream上传对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param stream 要上传的流
* @param stream 要上传的文件类型 MimeTypeUtils.IMAGE_JPEG_VALUE
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, InputStream stream,String contentType) {
boolean flag = bucketExists(bucketName);
if (flag) {
PutObjectOptions putObjectOptions = new PutObjectOptions(stream.available(), -1);
/**
* 开启公共类功能设置setContentType
*/
if (StringUtils.isNotBlank(contentType)) {
putObjectOptions.setContentType(contentType);
}
minioClient.putObject(bucketName, objectName, stream, putObjectOptions);
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 以流的形式获取一个文件对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(bucketName, objectName);
return stream;
}
}
return null;
}
/**
* 以流的形式获取一个文件对象(断点下载)
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param offset 起始字节的位置
* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(bucketName, objectName, offset, length);
return stream;
}
}
return null;
}
/**
* 下载并将文件保存到本地
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
*/
@SneakyThrows
public boolean getObject(String bucketName, String objectName, String fileName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
minioClient.getObject(bucketName, objectName, fileName);
return true;
}
}
return false;
}
/**
* 删除一个对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
*/
@SneakyThrows
public boolean removeObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(bucketName, objectName);
return true;
}
return false;
}
/**
* 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
*
* @param bucketName 存储桶名称
* @param objectNames 含有要删除的多个object名称的迭代器对象
* @return
*/
@SneakyThrows
public List<String> removeObject(String bucketName, List<String> objectNames) {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}
/**
* 生成一个给HTTP GET请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
@SneakyThrows
public String presignedGetObject(String bucketName, String objectName, Integer expires) {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
throw new InvalidExpiresRangeException(expires,
"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
}
url = minioClient.presignedGetObject(bucketName, objectName, expires);
}
return url;
}
/**
* 生成一个给HTTP PUT请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
@SneakyThrows
public String presignedPutObject(String bucketName, String objectName, Integer expires) {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
throw new InvalidExpiresRangeException(expires,
"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
}
url = minioClient.presignedPutObject(bucketName, objectName, expires);
}
return url;
}
/**
* 获取对象的元数据
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public ObjectStat statObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = minioClient.statObject(bucketName, objectName);
return statObject;
}
return null;
}
/**
* 文件访问路径
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public String getObjectUrl(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
url = minioClient.getObjectUrl(bucketName, objectName);
}
return url;
}
public void downloadFile(String bucketName, String filePath, String originalName, HttpServletResponse response) {
try {
InputStream file = minioClient.getObject(bucketName, filePath);
if (StringUtils.isNotEmpty(originalName)) {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(originalName,"UTF-8"));
}else{
String filename = new String(filePath.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
}
ServletOutputStream servletOutputStream = response.getOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len = file.read(buffer)) > 0) {
servletOutputStream.write(buffer, 0, len);
}
servletOutputStream.flush();
file.close();
servletOutputStream.close();
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
源码地址:https://gitee.com/zym213/springboot-minio.git
下一篇说一下如何用nginx做minio的负载均衡