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 ;
        }
    }
}
相关推荐
蒙娜丽宁7 分钟前
深入理解Go语言中的接口定义与使用
开发语言·后端·golang·go
dawn1912289 分钟前
SpringMVC 中的域对象共享数据
java·前端·servlet
Xwzzz_12 分钟前
Nginx配置负载均衡
java·nginx·负载均衡
小叶子来了啊15 分钟前
002.k8s(Kubernetes)一小时快速入门(先看docker30分钟)
java·容器·kubernetes
DKPT27 分钟前
数据结构之快速排序、堆排序概念与实现举例
java·数据结构·算法
尘浮生30 分钟前
Java项目实战II基于Java+Spring Boot+MySQL的校园社团信息管理系统(源码+数据库+文档)
java·开发语言·数据库·spring boot·mysql·spring·maven
不染_是非1 小时前
Django学习实战篇六(适合略有基础的新手小白学习)(从0开发项目)
后端·python·学习·django
lj9077226441 小时前
Dockerfile部署xxljob
java·docker
代码对我眨眼睛1 小时前
springboot从分层到解耦
spring boot·后端
多则惑少则明1 小时前
idea 编辑器常用插件集合
java·编辑器·intellij-idea