sky-take-out/sky-common/src/main/java/com/sky/common/utils/MinioUtils.java

112 lines
3.1 KiB
Java
Raw Normal View History

2024-03-11 21:14:14 +08:00
package com.sky.common.utils;
2024-03-12 17:58:59 +08:00
import com.sky.common.properties.MinioProperties;
2024-03-11 21:14:14 +08:00
import io.minio.*;
2024-03-16 21:54:38 +08:00
import lombok.RequiredArgsConstructor;
2024-03-11 21:14:14 +08:00
import lombok.extern.slf4j.Slf4j;
2024-03-12 17:58:59 +08:00
import org.springframework.stereotype.Component;
2024-03-11 21:14:14 +08:00
import java.io.InputStream;
2024-03-12 17:58:59 +08:00
@Component
2024-03-16 21:54:38 +08:00
@RequiredArgsConstructor
2024-03-11 21:14:14 +08:00
@Slf4j
public class MinioUtils {
2024-03-16 21:54:38 +08:00
private final MinioClient minioClient;
private final MinioProperties minioProperties;
2024-03-11 21:14:14 +08:00
/**
* 判断桶是否存在
*
* @param bucketName String
* @return found
*/
public boolean bucketExists(String bucketName) {
boolean found = false;
try {
found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
e.printStackTrace();
}
return found;
}
/**
* 如果桶不存在就新建
*
* @param bucketName String
*/
public void bucketCreate(String bucketName) {
boolean exists = bucketExists(bucketName);
if (!exists) {
try {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 上传文件
*
* @param fileName 文件名
* @param inputStream 输入流
* @param size 文件大小
*/
public String uploadFile(String bucketName, String fileName, InputStream inputStream, Long size) {
try {
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.stream(inputStream, size, -1)
.build());
2024-03-12 17:58:59 +08:00
return minioProperties.getEndpointUrl() + "/" + bucketName + "/" + fileName;
2024-03-11 21:14:14 +08:00
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 上传文件
*
* @param fileName 文件名
* @param inputStream 输入流
* @param size 文件大小
* @param contentType 文件类型
*/
public String uploadFile(String bucketName, String fileName, InputStream inputStream, Long size, String contentType) {
try {
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.stream(inputStream, size, -1)
.contentType(contentType)
.build());
2024-03-12 17:58:59 +08:00
return minioProperties.getEndpointUrl() + "/" + bucketName + "/" + fileName;
2024-03-11 21:14:14 +08:00
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取文件
*
* @param bucketName 桶名称
* @param fileName 对象名称
*/
public InputStream getFile(String bucketName, String fileName) {
try {
return minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}