javafx-tools-minio/src/main/java/com/zhangmeng/minio/utils/MinioUtils.java

328 lines
13 KiB
Java
Raw Normal View History

2024-03-08 10:20:49 +00:00
package com.zhangmeng.minio.utils;
import com.zhangmeng.minio.model.BucketFile;
import io.minio.*;
2024-03-10 10:30:33 +00:00
import io.minio.errors.*;
2024-03-08 10:20:49 +00:00
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import javafx.application.Platform;
2025-07-07 07:32:10 +00:00
2024-03-08 10:20:49 +00:00
2024-03-10 10:30:33 +00:00
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
2024-03-08 10:20:49 +00:00
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author zhangmeng
* @version 1.0
* @date 2024-03-07 15:45
*/
public class MinioUtils {
private static MinioClient minioClient = null;
public static Map<String,Object> objectMap = new HashMap<>();
public static String current_bucket = "current_bucket";
public static String primaryStage = "primaryStage";
public static String bucket_choose_action_stage = "bucket_choose_action_stage";
public static String minioController = "minioController";
public static MinioClient getDefault() {
if (minioClient == null) {
2024-03-10 08:16:07 +00:00
Object endpoint = objectMap.get("endpoint");
Object accessKey = objectMap.get("accessKey");
Object secretKey = objectMap.get("secretKey");
if (endpoint == null ){
Platform.runLater(()->{
AlertUtils.alert_warning("配置文件endpoint 为空");
});
return null;
}
if (accessKey == null ){
Platform.runLater(()->{
AlertUtils.alert_warning("配置文件accessKey 为空");
});
return null;
}
if (secretKey == null ){
Platform.runLater(()->{
AlertUtils.alert_warning("配置文件secretKey 为空");
});
return null;
}
minioClient = MinioClient.builder().endpoint(endpoint.toString()).credentials(accessKey.toString(), secretKey.toString()).build();
2024-03-08 10:20:49 +00:00
}
return minioClient;
}
/**
* Bucket
*
* @return
*/
public static List<Bucket> getAllBuckets() {
2024-03-10 10:30:33 +00:00
try {
return getDefault().listBuckets();
2025-07-07 07:32:10 +00:00
} catch (ErrorResponseException | InsufficientDataException | InvalidKeyException | InternalException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
2025-07-07 09:11:26 +00:00
// e.printStackTrace();
Platform.runLater(()->{
AlertUtils.alert_warning("获取Bucket列表失败,请核对配置信息");
});
2024-03-10 10:30:33 +00:00
}
return null;
2024-03-08 10:20:49 +00:00
}
/**
* SpringBootBucket
* Bucket
*
* @param bucketName
*/
public static void createBucket(String bucketName) {
if (!bucketExists(bucketName)) {
2024-03-10 10:30:33 +00:00
try {
getDefault().makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
2025-07-07 07:32:10 +00:00
} catch (ErrorResponseException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | XmlParserException | ServerException | InsufficientDataException e) {
2024-03-10 10:30:33 +00:00
e.printStackTrace();
}
2024-03-08 10:20:49 +00:00
}else {
Platform.runLater(()->{
AlertUtils.alert_warning("bucket_name : "+ bucketName + "已存在");
});
}
}
/**
* Buckettruefalse
*
* @param bucketName
* @return
*/
2024-03-10 10:30:33 +00:00
public static Boolean bucketExists(String bucketName) {
try {
return getDefault().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
2025-07-07 07:32:10 +00:00
} catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidResponseException | NoSuchAlgorithmException | XmlParserException | ServerException | IOException | InvalidKeyException e) {
2024-03-10 10:30:33 +00:00
e.printStackTrace();
}
return null;
2024-03-08 10:20:49 +00:00
}
public String DateFormatString(ZonedDateTime zonedDateTime){
// 创建一个 DateTimeFormatter 对象,用于定义日期和时间的格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 使用 formatter 来格式化 ZonedDateTime 对象
return zonedDateTime.format(formatter);
}
/**
*
*
* @param bucketName
* @param prefix
* @param recursive 使
* @return MinioItem
*/
public static List<Item> getAllObjectsByPrefix(String bucketName,
String prefix,
boolean recursive) {
List<Item> list = new ArrayList<>();
Iterable<Result<Item>> objectsIterator = getDefault().listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
if (objectsIterator != null) {
for (Result<Item> o : objectsIterator) {
2024-03-10 10:30:33 +00:00
Item item = null;
try {
item = o.get();
2025-07-07 07:32:10 +00:00
} catch (ErrorResponseException | InsufficientDataException | InvalidKeyException |
InvalidResponseException | InternalException | IOException | NoSuchAlgorithmException |
ServerException | XmlParserException e) {
2024-03-10 10:30:33 +00:00
e.printStackTrace();
}
2024-03-08 10:20:49 +00:00
list.add(item);
}
}
return list;
}
/**
*
*
* @param bucketName
* @param objectName
* @return url
*/
public static String getPresignedObjectUrl(String bucketName, String objectName) {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.method(Method.GET).build();
2024-03-10 10:30:33 +00:00
try {
return getDefault() .getPresignedObjectUrl(args);
2025-07-07 07:32:10 +00:00
} catch (ErrorResponseException | InsufficientDataException | InvalidKeyException | InvalidResponseException | NoSuchAlgorithmException | ServerException | XmlParserException | IOException | InternalException e) {
2024-03-10 10:30:33 +00:00
e.printStackTrace();
}
return null;
2024-03-08 10:20:49 +00:00
}
public static List<BucketFile> getFileList(String bucketName){
List<Item> itemList = getAllObjectsByPrefix(bucketName, null, true);
List<BucketFile> list = new ArrayList<>();
if (itemList.size() > 0 ){
list = itemList.stream().map(i -> {
BucketFile bucketFile = new BucketFile();
2024-03-10 08:16:07 +00:00
bucketFile.setBucketName(bucketName);
2024-03-08 10:20:49 +00:00
bucketFile.setDir(i.isDir());
bucketFile.setFileName(i.objectName());
bucketFile.setSize(i.size());
//获取url
String presignedObjectUrl = getPresignedObjectUrl(bucketName, i.objectName());
bucketFile.setUrl(presignedObjectUrl);
return bucketFile;
}).collect(Collectors.toList());
}
return list;
}
public static void upload_file(File file){
//文件名
String fileName = file.getName();
2025-07-07 07:32:10 +00:00
String newFileName = System.currentTimeMillis() + "." + getFileExtension(fileName);
2024-03-08 10:20:49 +00:00
String contentType = getContentType(file);
String bucketName = objectMap.get(current_bucket).toString();
if (bucketName == null){
AlertUtils.alert_warning("上传的bucket不能为空!");
return;
}
uploadFile(bucketName, file, newFileName, contentType);
}
2025-07-07 08:01:33 +00:00
public static String upload_file(File file,String path){
//文件名
String fileName = file.getName();
String newFileName = System.currentTimeMillis() + "." + getFileExtension(fileName);
String contentType = getContentType(file);
String bucketName = objectMap.get(current_bucket).toString();
if (bucketName == null){
AlertUtils.alert_warning("上传的bucket不能为空!");
return null;
}
uploadFile(bucketName, file, path + "/" + newFileName, contentType);
return path + "/" + newFileName;
}
2025-07-07 07:32:10 +00:00
public static String getContentType(File file) {
String fileName = file.getName();
String extension = getFileExtension(fileName).toLowerCase();
return switch (extension) {
case "jpg", "jpeg" -> "image/jpeg";
case "png" -> "image/png";
case "mp4" -> "video/mp4";
case "gif" -> "image/gif";
case "txt" -> "text/plain";
case "pdf" -> "application/pdf";
case "doc" -> "application/msword";
case "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "xls" -> "application/vnd.ms-excel";
case "xlsx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "ppt" -> "application/vnd.ms-powerpoint";
case "pptx" -> "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case "zip" -> "application/zip";
case "tar" -> "application/x-tar";
case "json" -> "application/json";
case "html" -> "text/html";
case "css" -> "text/css";
case "js" -> "application/javascript";
case "mp3" -> "audio/mp3";
case "wav" -> "audio/wav";
case "flac" -> "audio/flac";
case "aac" -> "audio/aac";
case "ogg" -> "audio/ogg";
case "avi" -> "video/avi";
case "mov" -> "video/quicktime";
case "wmv" -> "video/x-ms-wmv";
case "mkv" -> "video/x-matroska";
case "flv" -> "video/x-flv";
case "swf" -> "application/x-shockwave-flash";
case "psd" -> "image/vnd.adobe.photoshop";
case "ai" -> "application/postscript";
case "eps" -> "application/postscript";
case "ps" -> "application/postscript";
case "svg" -> "image/svg+xml";
case "tif" -> "image/tiff";
case "tiff" -> "image/tiff";
case "ico" -> "image/x-icon";
case "md" -> "text/markdown";
case "yaml" -> "text/yaml";
case "yml" -> "text/yaml";
case "xml" -> "text/xml";
case "csv" -> "text/csv";
case "tsv" -> "text/tab-separated-values";
case "jsonl" -> "application/json-seq";
case "bin" -> "application/octet-stream";
case "exe" -> "application/octet-stream";
case "dll" -> "application/octet-stream";
case "so" -> "application/octet-stream";
case "class" -> "application/octet-stream";
case "war" -> "application/octet-stream";
case "ear" -> "application/octet-stream";
case "rar" -> "application/octet-stream";
case "gz" -> "application/gzip";
default -> "application/octet-stream";
};
}
// 原生 Java 的等价方法
public static String getFileExtension(String fileName) {
if (fileName == null) return "";
int lastDotIndex = fileName.lastIndexOf('.');
// 判断没有点,或者点是第一个字符(例如 ".gitignore"
if (lastDotIndex == -1 || lastDotIndex == 0) {
return fileName;
}
return fileName.substring(lastDotIndex + 1);
}
2024-03-08 10:20:49 +00:00
/**
* 使MultipartFile
*
* @param bucketName
* @param file
* @param objectName
* @param contentType
* @return
*/
public static ObjectWriteResponse uploadFile(String bucketName, File file, String objectName, String contentType) {
2024-03-10 10:30:33 +00:00
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(contentType)
.stream(inputStream,inputStream.available(), -1)
.build());
2025-07-07 07:32:10 +00:00
} catch (IOException | XmlParserException | InternalException | InvalidKeyException | ErrorResponseException | ServerException | InsufficientDataException | InvalidResponseException | NoSuchAlgorithmException e) {
2024-03-10 10:30:33 +00:00
e.printStackTrace();
} finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
2024-03-08 10:20:49 +00:00
}
}