1、導入 minio jar包
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.1.0</version>
</dependency>
2、配置
application.yml 配置
minio:
endpoint: 172.0.0.1
port: 9000
accessKey: minio
secretKey: miniopassword
secure: false
bucketName: "my-bucket"
configDir: "/home/data/"
類配置
/**
* minio配置
*/
public static class Minio{
/**
* minio地址
*/
public static String Url="http://127.0.0.1:9000";
/**
* AK
*/
public static String AccessKey="minio";
/**
* SK
*/
public static String SecretKey="miniopassword";
/**
* 文件夾
*/
public static String BuckeName="my-buckeName";
}
3、實現
package com.minio.config;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
@ApiModelProperty("endPoint是一個URL,域名,IPv4或者IPv6地址")
private String endpoint;
@ApiModelProperty("TCP/IP端口號")
private int port;
@ApiModelProperty("accessKey類似於用戶ID,用於唯一標識你的賬戶")
private String accessKey;
@ApiModelProperty("secretKey是你賬戶的密碼")
private String secretKey;
@ApiModelProperty("如果是true,則用的是https而不是http,默認值是true")
private Boolean secure;
@ApiModelProperty("默認存儲桶")
private String bucketName;
@ApiModelProperty("配置目錄")
private String configDir;
@Bean
public MinioClient getMinioClient() throws InvalidEndpointException, InvalidPortException {
MinioClient minioClient = new MinioClient(endpoint, port, accessKey, secretKey,secure);
return minioClient;
}
}
util:
package com.hope.minio.utils;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @PackageName: com.hope.minio.utils
* @ClassName: MinioUtil
* @Author Hope
* @Date 2020/7/27 11:43
* @Description: TODO
*/
@Component
public class MinioUtil {
@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 要上傳的流
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, InputStream stream) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
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 fileName, String originalName, HttpServletResponse response) {
try {
InputStream file = minioClient.getObject(bucketName, fileName);
String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
if (StringUtils.isNotEmpty(originalName)) {
fileName = originalName;
}
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();
}
}
}
注意:存儲桶命名要求
存儲桶的命名需符合以下一個或多個規則
. 存儲桶名稱的長度介於 3 和 63 個字符之間,並且只能包含小寫字母、數字、句點和短划線。
. 存儲桶名稱中的每個標簽必須以小寫字母或數字開頭。
. 存儲桶名稱不能包含下划線、以短划線結束、包含連續句點或在句點旁邊使用短划線。
. 存儲桶名稱不能采用 IP 地址格式 (198.51.100.24)。
. 存儲桶用作可公開訪問的 URL,因此您選擇的存儲桶名稱必須具有全局唯一性。如果您選擇的名稱已被其他一些帳戶用於創建存儲桶,則必須使用其他名稱。
4、使用
/**
* 批量導入 minio
*/
public void importFiles(MultipartFile[] files) throws IOException {
for(int i=0;i<files.length;i++){
InputStream fileInputStream = files[i].getInputStream();
// 獲取原文件名 eg: test.xlsx
String fileName=files[i].getOriginalFilename();
// 文件前綴 eg: test
String preName= FileUtil.getPrefix(fileName);
// 文件后綴 eg: xlsx
String sufName= FileUtil.getSuffix(fileName);
// 確保文件名唯一性
String saveFileName=preName+ StrUtil.UNDERLINE+ DateUtil.format(DateUtil.date(),
DatePattern.PURE_DATETIME_MS_PATTERN)+StrUtil.DOT+sufName;
// 創建桶
MinioUtil.makeBucket("save-files");
// 上傳文件
MinioUtil.putObject("save-files",saveFileName,fileInputStream);
}
}
工具類
package com.zl.utils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import java.io.InputStream;
/**
* minio工具
*/
@Component
public class MinioUtil {
/**
* minio參數
*/
@Value("${minio.endpoint}")
private String ENDPOINT;
@Value(("${minio.accessKey}"))
private String ACCESS_KEY;
@Value("${minio.secretKey}")
private String SECRET_KEY;
/**
* 上傳本地文件
*
* @param bucket 桶
* @param objectKey 文件key
* @param filePath 文件路徑
* @return 文件url
*/
public String upload(String bucket, String objectKey, String filePath){
return upload(bucket, objectKey, filePath, MediaType.APPLICATION_OCTET_STREAM_VALUE);
}
/**
* 上傳本地文件
*
* @param bucket 桶
* @param objectKey 文件key
* @param filePath 文件路徑
* @param contentType 文件類型
* @return 文件url
*/
public String upload(String bucket, String objectKey, String filePath, String contentType) {
try {
MinioClient client = MinioClient.builder().endpoint(ENDPOINT).credentials(ACCESS_KEY, SECRET_KEY).build();
client.uploadObject(UploadObjectArgs.builder().bucket(bucket).object(objectKey).contentType(contentType).filename(filePath).build());
} catch (Exception e) {
e.printStackTrace();
}
return getObjectPrefixUrl(bucket, objectKey);
}
/**
* 流式上傳文件
*
* @param bucket 桶
* @param objectKey 文件key
* @param inputStream 文件輸入流
* @return 文件url
*/
public String upload(String bucket, String objectKey, InputStream inputStream){
return upload(bucket, objectKey, inputStream, MediaType.APPLICATION_OCTET_STREAM_VALUE);
}
/**
* 流式上傳文件
*
* @param bucket 桶
* @param objectKey 文件key
* @param inputStream 文件輸入流
* @param contentType 文件類型
* @return 文件url
*/
public String upload(String bucket, String objectKey, InputStream inputStream, String contentType) {
try {
MinioClient client = MinioClient.builder().endpoint(ENDPOINT).credentials(ACCESS_KEY, SECRET_KEY).build();
client.putObject(PutObjectArgs.builder().bucket(bucket).object(objectKey).stream(inputStream, inputStream.available(), -1).contentType(contentType).build());
} catch (Exception e) {
e.printStackTrace();
}
return getObjectPrefixUrl(bucket, objectKey);
}
/**
* 文件url前半段
*
* @param bucket 桶
* @return 前半段文件url
*/
private String getObjectPrefixUrl(String bucket, String objectKey) {
return String.format("%s/%s/%s", ENDPOINT, bucket, objectKey);
}
/**
* 截取永久地址
*
* @param imgUrl 上傳文件地址
*/
private String getPrefixUrl(String imgUrl) {
return imgUrl.split("\\?")[0];
}
}
5、上傳圖片設置文件類型
minioTemplate.putObject(bucketName, saveFileName, fileInputStream, fileInputStream.available(), ViewContentType.getContentType(fileName));
public enum ViewContentType {
DEFAULT("default","application/octet-stream"),
JPG("jpg", "image/jpeg"),
TIFF("tiff", "image/tiff"),
GIF("gif", "image/gif"),
JFIF("jfif", "image/jpeg"),
PNG("png", "image/png"),
TIF("tif", "image/tiff"),
ICO("ico", "image/x-icon"),
JPEG("jpeg", "image/jpeg"),
WBMP("wbmp", "image/vnd.wap.wbmp"),
FAX("fax", "image/fax"),
NET("net", "image/pnetvue"),
JPE("jpe", "image/jpeg"),
RP("rp", "image/vnd.rn-realpix");
private String prefix;
private String type;
public static String getContentType(String prefix){
if(StrUtil.isEmpty(prefix)){
return DEFAULT.getType();
}
prefix = prefix.substring(prefix.lastIndexOf(".") + 1);
for (ViewContentType value : ViewContentType.values()) {
if(prefix.equalsIgnoreCase(value.getPrefix())){
return value.getType();
}
}
return DEFAULT.getType();
}
ViewContentType(String prefix, String type) {
this.prefix = prefix;
this.type = type;
}
public String getPrefix() {
return prefix;
}
public String getType() {
return type;
}
}
6、更改限時鏈接設置為永久
使用官方api的方式獲取臨時鏈接(client.getPresignedObjectUrl),只有七天,很不方便。
添加匹配策略
設置匹配前綴,再選擇Read Only 或 Read and Write后點擊添加即可。
- 當填寫前綴
*
默認該存儲空間(Bucket)下所有文件都可以訪問 - 當填寫特殊前綴對應該存儲空間(Bucket)下特定這個前綴開頭文件可以訪問,如此處設置以下
d
開頭的前綴,那么便只有d開頭的文件可以公開訪問。
原來地址:
http://57.21.9.13:9001/an-event/3_20221114165654357.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20221114%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221114T085654Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=8f8f54d4112ca9cc82fc8a20ad24788ebd5a7fffdcf36cb67e9a26d865b0c160
使用地址 ?
前的鏈接就可以永久訪問 http://57.21.9.13:9001/an-event/3_20221114165654357.jpg
參考地址:
https://blog.csdn.net/weixin_37264997/article/details/107631796