<minio.version>8.3.4</minio.version>
<!-- 其它 && 数据源加密 -->
<org.bouncycastle.bcprov-jdk15on.version>1.70</org.bouncycastle.bcprov-jdk15on.version>
<dependencies>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>${minio.version}</version>
</dependency>
<!-- 数据源加解密 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${org.bouncycastle.bcprov-jdk15on.version}</version>
</dependency>
<!--错误:springboot 配置顶上爆红-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
import com.sunyard.staging.starter.minio.utils.AesCbcUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Setter
@Getter
@Configuration
@ConfigurationProperties(prefix = "spring.minio")
public class MinioConfig {
private String endpoint;
private String accessKey;
private String secretKey;
@Bean
public io.minio.MinioClient minioClient(){
return io.minio.MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, AesCbcUtil.Decrypt(secretKey))
.build();
}
}
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class MinioService {
@Resource
private MinioClient minioClient;
public Boolean bucketExists(String bucketName) {
Boolean found;
try {
found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
log.error("查看存储bucket是否存在出现异常",e);
return false;
}
return found;
}
public Boolean makeBucket(String bucketName) {
try {
minioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
log.error("创建存储bucket出现异常",e);
return false;
}
return true;
}
public Boolean removeBucket(String bucketName) {
try {
minioClient.removeBucket(RemoveBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
log.error("删除存储bucket出现异常",e);
return false;
}
return true;
}
public List<Bucket> getAllBuckets() {
try {
return minioClient.listBuckets();
} catch (Exception e) {
log.error("获取全部bucket出现异常",e);
}
return null;
}
public Boolean upload(MultipartFile file,String bucketName) {
String fileName = "2021-07/21/";
fileName = fileName+file.getOriginalFilename();
try {
PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
.stream(file.getInputStream(),file.getSize(),-1).contentType(file.getContentType()).build();
minioClient.putObject(objectArgs);
} catch (Exception e) {
log.error("文件上传出现异常",e);
return false;
}
return true;
}
public String preview(String fileName,String bucketName){
GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(fileName).method(Method.GET).build();
try {
String url = minioClient.getPresignedObjectUrl(build);
return url;
} catch (Exception e) {
log.error("预览图片出现异常",e);
}
return null;
}
public void download(String fileName, HttpServletResponse res, String bucketName) {
GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
.object(fileName).build();
try (GetObjectResponse response = minioClient.getObject(objectArgs)){
byte[] buf = new byte[1024];
int len;
try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
while ((len=response.read(buf))!=-1){
os.write(buf,0,len);
}
os.flush();
byte[] bytes = os.toByteArray();
res.setCharacterEncoding("utf-8");
res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
try (ServletOutputStream stream = res.getOutputStream()){
stream.write(bytes);
stream.flush();
}
}
} catch (Exception e) {
log.error("文件下载出现异常",e);
}
}
public List<Item> listObjects(String bucketName) {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).build());
List<Item> items = new ArrayList<>();
try {
for (Result<Item> result : results) {
items.add(result.get());
}
} catch (Exception e) {
log.error("查看文件对象出现异常",e);
return null;
}
return items;
}
public boolean remove(String fileName,String bucketName){
try {
minioClient.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
}catch (Exception e){
log.error("删除文件出现异常",e);
return false;
}
return true;
}
public Iterable<Result<DeleteError>> removeObjects(List<String> objects,String bucketName) {
List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
return results;
}
}
import com.google.common.io.FileBackedOutputStream;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
@Component
public class MinioUtil {
@Resource
private MinioClient minioClient;
String constantBucket = "home" ;
public Boolean bucketExists(String bucketName) {
Boolean found;
try {
found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
return false;
}
return found;
}
public Boolean makeBucket(String bucketName) {
try {
minioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
return false;
}
return true;
}
public Boolean makeFolderPath( String folderPath) {
try {
folderPath = folderPath.substring(folderPath.indexOf('/'));
minioClient.putObject(PutObjectArgs.builder()
.bucket(constantBucket).object(folderPath).stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
.build());
} catch (Exception e) {
return false;
}
return true;
}
public Boolean removeBucket(String bucketName) {
try {
minioClient.removeBucket(RemoveBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
return false;
}
return true;
}
public List<Bucket> getAllBuckets() {
try {
return minioClient.listBuckets();
} catch (Exception e) {
return null;
}
}
public Boolean upload(MultipartFile file, String bucketName, String fileName) {
try {
fileName = fileName.substring(fileName.indexOf('/'));
PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
.stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
minioClient.putObject(objectArgs);
} catch (Exception e) {
return false;
}
return true;
}
public boolean uploadBypath(MultipartFile file, String filePath, String fileName) {
try {
String path = filePath + fileName;
path = path.substring(path.indexOf('/'));
PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(constantBucket).object(path)
.stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
minioClient.putObject(objectArgs);
} catch (Exception e) {
return false;
}
return true;
}
public String preview(String fileName, String bucketName) {
GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(fileName).method(Method.GET).build();
try {
String url = minioClient.getPresignedObjectUrl(build);
return url;
} catch (Exception e) {
return "查看失败";
}
}
public String download(String fileName, HttpServletResponse res) {
GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(constantBucket)
.object(fileName).build();
try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
byte[] buf = new byte[1024];
int len;
try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
while ((len = response.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
byte[] bytes = os.toByteArray();
res.setCharacterEncoding("utf-8");
res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
try (ServletOutputStream stream = res.getOutputStream()) {
stream.write(bytes);
stream.flush();
}
}
return "downloadSuccess";
} catch (Exception e) {
return "downloadFailed";
}
}
@SneakyThrows
public String downloadByPath(String filePath, HttpServletResponse res) {
Iterable<Result<Item>> myObjects;
myObjects = minioClient.listObjects(ListObjectsArgs.builder()
.bucket(constantBucket)
.prefix(filePath)
.recursive(true)
.build());
List<String> filePaths = new ArrayList<>();
for (Result<Item> result : myObjects) {
Item item = result.get();
filePaths.add(item.objectName());
}
ZipOutputStream zipos = null;
DataOutputStream os = null;
InputStream is = null;
try {
res.reset();
String zipName = new String(URLEncoder.encode("test", "UTF-8").getBytes(), StandardCharsets.ISO_8859_1);
res.setHeader("Content-Disposition", "attachment;fileName=\"" + zipName + ".zip\"");
zipos = new ZipOutputStream(new BufferedOutputStream(res.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);
for (int i = 0; i < filePaths.size(); i++) {
String file = filePaths.get(i);
String packageName = filePaths.get(i).replace(filePath + "/", "");
try {
zipos.putNextEntry(new ZipEntry(packageName));
os = new DataOutputStream(zipos);
is = minioClient.getObject(GetObjectArgs.builder().bucket(constantBucket).object(file).build());
byte[] b = new byte[1024];
int length = 0;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
is.close();
os.flush();
os.close();
zipos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (zipos != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return "downloadSucess";
}
public List<Item> listObjects(String bucketName) {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).build());
List<Item> items = new ArrayList<>();
try {
for (Result<Item> result : results) {
items.add(result.get());
}
} catch (Exception e) {
return null;
}
return items;
}
public List<Item> listFileObjects( String filePath) {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder()
.bucket(constantBucket)
.prefix(filePath)
.recursive(true).build()
);
List<Item> items = new ArrayList<>();
try {
for (Result<Item> result : results) {
items.add(result.get());
}
} catch (Exception e) {
return null;
}
return items;
}
public boolean remove(String fileName) {
try {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(constantBucket).object(fileName).build());
} catch (Exception e) {
return false;
}
return true;
}
public Iterable<Result<DeleteError>> removeObjects(List<String> objects, String bucketName) {
List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
return results;
}
@SneakyThrows
public boolean removeMedFile( String minioPath) {
minioPath = minioPath.substring(minioPath.indexOf('/') + 1);
Iterable<Result<Item>> listResults = minioClient.listObjects(
ListObjectsArgs.builder()
.bucket(constantBucket)
.prefix(minioPath)
.recursive(true).build()
);
List<DeleteObject> objects = new LinkedList<>();
for (Result<Item> listResult : listResults) {
Item item = listResult.get();
String itemName = item.objectName().toString();
System.out.println(itemName);
objects.add(new DeleteObject(itemName));
}
Iterable<Result<DeleteError>> results =
minioClient.removeObjects(
RemoveObjectsArgs.builder()
.bucket(constantBucket)
.objects(objects).build()
);
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
System.out.println(error.objectName());
}
return true;
}
@SneakyThrows
public boolean copyMedFile( String srcfilePath, String trgfilePath) {
try{
minioClient.copyObject(
CopyObjectArgs.builder()
.bucket(constantBucket)
.object(trgfilePath)
.source(
CopySource.builder()
.bucket(constantBucket)
.object(srcfilePath)
.build())
.build());
} catch(Exception e){
return false ;
}
return true ;
}
@SneakyThrows
public StatObjectResponse getAttachmentInfo( String filePath){
try{
StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder()
.bucket(constantBucket)
.object(filePath).build()) ;
return statObjectResponse ;
}catch(Exception e){
return null ;
}
}
}