springBoot整合minio

java 复制代码
<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>
java 复制代码
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 {
    //地址 http://172.1.0.79:9000
    private String endpoint;
    //minio账号
    private String accessKey;
    //minio密码
    private String secretKey;

    /**
     * 初始化minio连接池
     * @return MinioClient
     */
    @Bean
    public io.minio.MinioClient minioClient(){
        return io.minio.MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, AesCbcUtil.Decrypt(secretKey))
                .build();
    }
}
java 复制代码
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;

    /**
     * 查看存储bucket是否存在
     * @param bucketName
     * @return boolean
     */
    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;
    }

    /**
     * 创建存储bucket
     * @param bucketName
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.error("创建存储bucket出现异常",e);
            return false;
        }
        return true;
    }
    /**
     * 删除存储bucket
     * @param bucketName
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.error("删除存储bucket出现异常",e);
            return false;
        }
        return true;
    }
    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            log.error("获取全部bucket出现异常",e);
        }
        return null;
    }

    /**
     * 文件上传
     * @param file 文件
     * @param bucketName
     * @return Boolean
     */
    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;
    }

    /**
     * 预览图片
     * @param fileName
     * @param bucketName
     * @return
     */
    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;
    }

    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @param bucketName
     * @return Boolean
     */
    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.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            log.error("文件下载出现异常",e);
        }
    }

    /**
     * 查看文件对象
     * @param bucketName
     * @return 存储bucket内文件对象信息
     */
    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;
    }

    /**
     * 删除
     * @param fileName
     * @param bucketName
     * @return
     * @throws Exception
     */
    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;
    }

    /**
     * 批量删除文件对象(没测试)
     * @param bucketName
     * @param objects 对象名称集合
     */
    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;
    }
}
java 复制代码
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" ;
    /**
     * 查看存储bucket是否存在
     *
     * @param bucketName
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName
     * @return Boolean
     */
    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;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 文件上传
     *
     * @param file       文件
     * @param bucketName
     * @return Boolean
     */
    public Boolean upload(MultipartFile file, String bucketName, String fileName) {
        // 修饰过的文件名 非源文件名
        /*String fileName = "2021-07/21/";
        fileName = fileName+file.getOriginalFilename();*/
        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;
    }


    /**
     * 预览图片
     *
     * @param fileName
     * @param bucketName
     * @return
     */
    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 "查看失败";
        }
    }

    /**
     * 文件下载
     *
     * @param fileName   文件名称
     * @param res        response
     * @return Boolean
     */
    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.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }
            return "downloadSuccess";
        } catch (Exception e) {
            return "downloadFailed";
        }
    }

    /**
     * 批量下载某个文件下的所有文件 以压缩包的方式进行下载
     *
     * @param filePath
     * @param res
     **/
    @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";
    }


    /**
     * 查看文件对象
     *
     * @param bucketName
     * @return 存储bucket内文件对象信息
     */
    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;
    }


    /**
     * 查看文件目录下的文件对象
     *
     *
     * @param filePath
     * @return 文件目录下文件对象信息
     */

    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;
    }


    /**
     * 删除
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(constantBucket).object(fileName).build());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 批量删除文件对象(没测试)
     *
     * @param bucketName
     * @param objects    对象名称集合
     */
    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;
    }


    /**
     * 递归删除制定文件路径下的所有文件和文件夹
     * @param minioPath  文件路径
     */
    @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 ;
        }
    }
}
相关推荐
开心就好20252 分钟前
iOS App 加固方法的实际应用,安全不再只是源码问题
后端
冒泡的肥皂14 分钟前
AI小应用分享
人工智能·后端
quikai198127 分钟前
python练习第六组
java·前端·python
阿虎儿27 分钟前
本地部署docker完整版minIO镜像
后端
222you27 分钟前
线程的常用方法
java·开发语言
亚当28 分钟前
SpringBoot中使用MyBatis入门笔记
后端
诺斯贝克39 分钟前
Unable to create converter for xxx.NetworkResponse<Auth> for method AuthService
前端·后端
用户693717500138441 分钟前
29.Kotlin 类型系统:智能转换:类型检查 (is) 与类型转换 (as)
android·后端·kotlin
用户693717500138442 分钟前
30. Kotlin 扩展:为“老类”添“新衣”:扩展函数与扩展属性
android·后端·kotlin
是梦终空43 分钟前
JAVA毕业设计259—基于Java+Springboot+vue3工单管理系统的设计与实现(源代码+数据库+开题报告)
java·spring boot·vue·毕业设计·课程设计·工单管理系统·源代码