There are two classes, respectively is MinioClientSingleton class and MinioUtils. Class
pom.xml
<dependencies>
<! -- Minio file service -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.1.0</version>
</dependency>
</dependencies>
Copy the code
MinioClientSingleton.class
This is the miniO client singleton class, mainly reads the configuration information to build MinioClient; This utility class is provided for use by minioutils.class
import io.minio.MinioClient;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/** * minio client singleton class ** /
@Getter
@Component
public class MinioClientSingleton {
private static String domainUrl;
private static String accessKey;
private static String secretKey;
@Value("${min-io.endpoint}")
public void setDomainUrl(String domainUrl) {
MinioClientSingleton.domainUrl = domainUrl;
}
@Value("${min-io.accessKey}")
public void setAccessKey(String accessKey) {
MinioClientSingleton.accessKey = accessKey;
}
@Value("${min-io.secretKey}")
public void setSecretKey(String secretKey) {
MinioClientSingleton.secretKey = secretKey;
}
private volatile static MinioClient minioClient;
public MinioClientSingleton(a) {}/** * Get the minio client instance **@return {@link MinioClient}
*/
public static MinioClient getMinioClient(a) {
if (minioClient == null) {
synchronized (MinioClientSingleton.class) {
if (minioClient == null) { minioClient = MinioClient.builder() .endpoint(domainUrl) .credentials(accessKey, secretKey) .build(); }}}returnminioClient; }}Copy the code
MinioUtils.class
Main utility classes, including Upload, Get file stream (download), Delete, get preview path (return to me for front-end preview or download)
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/** * Minio client tool class */
@SuppressWarnings("ALL")
@Slf4j
public class MinioUtils {
/** * Create a file bucket (the recommended tenant ID is the bucket name) */
public static boolean exitsBucket(String bucket) {
boolean found = false;
try {
found = MinioClientSingleton.getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
} catch (Exception e) {
log.error("create bucket is error", e);
}
return found;
}
/** * Automatically creates buckets and stores files **@param inputStream
* @param fileName
* @param bucket
* @param fileSize
* @return* /
public static String putObjectStream(InputStream inputStream, String fileName, String bucket, Long fileSize) {
try {
boolean bucketExsit = exitsBucket(bucket);
if (bucketExsit) {
makeBucketPolicy(bucket);
}
MinioClientSingleton.getMinioClient().putObject(
PutObjectArgs.builder()
.bucket(bucket).object(fileName).stream(inputStream, fileSize, -1).build());
inputStream.close();
return MinioClientSingleton.getMinioClient().getObjectUrl(bucket, fileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/ * * *@paramBucket Bucket name *@paramPath Folder path [doc/] *@paramFile File to be uploaded *@paramFileName user-defined fileName *@return* /
public static String putObject(@NonNull String bucket, @NonNull String path, @NonNull MultipartFile file, String fileName) throws Exception {
if(! exitsBucket(bucket)) { makeBucketPolicy(bucket); } InputStream inputStream =null;
try {
MinioClientSingleton.getMinioClient().putObject(
PutObjectArgs.builder().bucket(bucket).object(path).stream(
new ByteArrayInputStream(new byte[] {}),0, -1)
.build());
inputStream = file.getInputStream();
if (StringUtils.isEmpty(fileName)) {
fileName = file.getOriginalFilename();
}
InputStream in = file.getInputStream();
PutObjectOptions options = new PutObjectOptions(in.available(), -1);
options.setContentType(file.getContentType());
String objectName = path + System.currentTimeMillis() + "_" + fileName; // Generate timestamps to prevent duplicate names
MinioClientSingleton.getMinioClient().putObject(bucket, objectName, in, options);
file.getInputStream().close();
in.close();
return MinioClientSingleton.getMinioClient().presignedGetObject(bucket, objectName);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(inputStream ! =null) { inputStream.close(); }}return null;
}
private static void makeBucketPolicy(String bucket) throws ErrorResponseException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, RegionConflictException, ServerException, XmlParserException {
String policyJsonBuilder = "{\n" +
""Statement": [\n" +
" {\n" +
""Action": [\n" +
""s3:GetBucketLocation",\n" +
""s3:ListBucket"\n" +
" ],\n" +
""Effect":"Allow",\n" +
""Principal":"*",\n" +
""Resource":"arn:aws:s3:::" + bucket + ""\n" +
" },\n" +
" {\n" +
""Action":"s3:GetObject",\n" +
""Effect":"Allow",\n" +
""Principal":"*",\n" +
""Resource":"arn:aws:s3:::" + bucket + "/*"\n" + " }\n" + " ],\n" + " "Version": "2012-10-17"\n" + "}\n"; MinioClientSingleton.getMinioClient().makeBucket(MakeBucketArgs.builder() .bucket(bucket) .build()); //noinspection deprecation MinioClientSingleton.getMinioClient().setBucketPolicy(bucket, policyJsonBuilder); } /** * automatically creates buckets and stores files ** @return */
public static String putObjectStream(MultipartFile file, String bucket) throws Exception {
boolean exsit = exitsBucket(bucket);
if(! exsit) { makeBucketPolicy(bucket); } String fileHeader =null;
try {
InputStream inputStream = file.getInputStream();
boolean bucketExsit = exitsBucket(bucket);
if (bucketExsit) {
MinioClientSingleton.getMinioClient().makeBucket(MakeBucketArgs.builder()
.bucket(bucket)
.build());
}
MinioClientSingleton.getMinioClient().putObject(
PutObjectArgs.builder()
.bucket(bucket).object(file.getOriginalFilename()).stream(inputStream, inputStream.available(), -1).build());
inputStream.close();
return MinioClientSingleton.getMinioClient().getObjectUrl(bucket, file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/** * Query all bucket files **@return* /
public static List<Bucket> getListBuckets(a) {
try {
return MinioClientSingleton.getMinioClient().listBuckets();
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
/** * delete file **@paramBucket Bucket name *@paramObjectName objectName *@return boolean
*/
public static boolean removeObject(String bucket, String objectName) {
try {
boolean exsit = exitsBucket(bucket);
if (exsit) {
// Remove myObject from mybucket. removeobjectargs.builder().bucket(bucketname).object(objectname).build()MinioClientSingleton.getMinioClient().removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build()) ;return true; }}catch (Exception e) {
log.error("removeObject", e);
}
return false;
}
/** * Delete files in batches **@paramBucket Bucket name *@paramObjectNames Object name *@return boolean
*/
public static boolean removeObjects(String bucket, List<String> objectNames) {
boolean exsit = exitsBucket(bucket);
if (exsit) {
try {
List<DeleteObject> objects = new LinkedList<>();
for (String str : objectNames) {
objects.add(newDeleteObject(str)); } MinioClientSingleton.getMinioClient().removeObjects(RemoveObjectsArgs.builder().bucket(bucket).objects(objects).build()) ;return true;
} catch (Exception e) {
log.error("removeObject", e); }}return false;
}
/** * Get all file object names ** in a single bucket@paramBucket Bucket name *@return {@link List}<{@link String}>
*/
public static List<String> getBucketObjectName(String bucket) {
boolean exsit = exitsBucket(bucket);
if (exsit) {
List<String> listObjetcName = new ArrayList<>();
try {
Iterable<Result<Item>> myObjects = MinioClientSingleton.getMinioClient().listObjects(ListObjectsArgs.builder().bucket(bucket).build());
for (Result<Item> result : myObjects) {
Item item = result.get();
listObjetcName.add(item.objectName());
}
return listObjetcName;
} catch(Exception e) { e.printStackTrace(); }}return null;
}
/** * gets a file object ** as a stream@paramBucket Bucket name *@paramObjectName objectName *@return {@link InputStream}
*/
public static InputStream getObjectInputStream(String bucket, String objectName) {
boolean exsit = exitsBucket(bucket);
if (exsit) {
try {
ObjectStat objectStat = MinioClientSingleton.getMinioClient().statObject(StatObjectArgs.builder().bucket(bucket).object(objectName).build());
if (objectStat.length() > 0) {
// Get the input stream for objectName.
returnMinioClientSingleton.getMinioClient().getObject(GetObjectArgs.builder().bucket(bucket).object(objectName).build()); }}catch(Exception e) { e.printStackTrace(); }}return null;
}
/** * delete a bucket **@paramBucket Indicates the bucket name */
public static boolean removeBucket(String bucket) throws Exception {
// Check whether 'my-bucket' exists before deleting it.
boolean found = exitsBucket(bucket);
if (found) {
Iterable<Result<Item>> myObjects = MinioClientSingleton.getMinioClient().listObjects(ListObjectsArgs.builder().bucket(bucket).build());
for (Result<Item> result : myObjects) {
Item item = result.get();
// If there are object files, deletion fails
if (item.size() > 0) {
return false; }}// Delete bucket 'bucketName'. Note that bucketName can be deleted only when the bucket is empty.
MinioClientSingleton.getMinioClient().removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
found = exitsBucket(bucket);
return! found; }return false;
}
/** * Gets the URL of an object under a bucket **@paramBucket Bucket name *@paramObjectName objectName (folder name + file name) *@return* /
public static String getBucketObject(String bucket, String objectName) throws Exception {
// Check whether 'my-bucket' exists before deleting it.
boolean found = exitsBucket(bucket);
if (found) {
return MinioClientSingleton.getMinioClient().getObjectUrl(bucket, objectName);
}
return "";
}
/** * Get the absolute address of the preview file from the file path **@paramBucket Bucket name *@paramObjectName objectName (folder name + file name) *@return* /
public String getPreviewFileUrl(String bucket, String objectName) {
try {
return MinioClientSingleton.getMinioClient().presignedGetObject(bucket, objectName);
} catch (Exception e) {
e.printStackTrace();
return ""; }}}Copy the code
Controller.class
@RestController
@RequestMapping("/api/notice")
public class ProductNoticeController {
@PostMapping("/file/upload")
@apiOperation (value = "upload file ", notes =" upload file ")
public JsonResult upload(MultipartFile file) {
try {
String url = MinioUtils.putObject(bucket, "notice/", file, file.getOriginalFilename());
return JsonResult.ok().build(url);
} catch (Exception e) {
e.printStackTrace();
return JsonResult.error("upload.error"."Upload failed").build(); }}}Copy the code