Spring Boot配置MinIO(实现文件上传、读取、下载、删除)

时间:2025-03-17 16:51:15

一、 MinIO

    MinIO 是一个基于Apache License v2.0开源协议的对象存储服务。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。

    MinIO是一个非常轻量的服务,可以很简单的和其他应用的结合,类似 NodeJS, Redis 或者 MySQL。

二、 MinIO安装和启动

   由于MinIO是一个单独的服务器,需要单独部署,有关MinIO在Windows系统上的使用请查看以下博客。

Windows MinIO使用教程(启动,登录,修改密码)

三、 (maven依赖文件)

    <dependency>
        <groupId></groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
    <!-- SpringBoot Web容器 -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>minio</artifactId>
        <version>8.3.4</version>
    </dependency>

四、 (配置文件)

设置单个文件大小

-file-size= 50MB
#minio文件服务器配置
=http://localhost:9000
=admin
=admin123
=test

五、 编写Java业务类

    minio涉及到的方法有:判断存储桶是否存在,创建存储桶,上传文件,读取文件、下载文件,删除文件等操作

1、StorageProperty 存储属性类:

import ;
import ;
import ;
 
 
/**
 * @Author yang
 * @Date 2023/1/3 14:00
 * @Version 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "s3")
public class StorageProperty {
    private String url;
    private String accessKey;
    private String secretKey;
//    private long callTimeOut = 60000;
//    private long readTimeOut = 300000;
}

2、minio 配置类:

import ;
import ;
import ;
import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
 
import ;
import ;
 
/**
 * @Author yang
 * @Date 2023/1/3 14:03
 * @Version 1.0
 */
@Slf4j
@Component
@Configuration
public class MinioClientConfig {
 
    @Autowired
    private StorageProperty storageProperty;
 
    private static MinioClient minioClient;
 
 
    /**
     * @description: 获取minioClient
     * @date 2021/6/22 16:55
     * @return 
     */
    public static MinioClient getMinioClient(){
        return minioClient;
    }
 
    /**
     * 判断 bucket是否存在
     *
     * @param bucketName:
     *            桶名
     * @return: boolean
     * @date : 2020/8/16 20:53
     */
    @SneakyThrows()
    public static boolean bucketExists(String bucketName) {
        return (().bucket(bucketName).build());
    }
 
 
    /**
     * 获取全部bucket
     *
     * @param :
     * @return: <>
     * @date : 2020/8/16 23:28
     */
    @SneakyThrows()
    public static List<Bucket> getAllBuckets() {
        return ();
    }
 
    /**
     * 初始化minio配置
     *
     * @param :
     * @return: void
     * @date : 2020/8/16 20:56
     */
    @PostConstruct
    public void init() {
        try {
            minioClient = ()
                    .endpoint(())
                    .credentials((), ())
                    .build();
        } catch (Exception e) {
            ();
            ("初始化minio配置异常: 【{}】", ());
        }
    }
 
}

3、minio工具类

i


mport .*;
 
import .slf4j.Slf4j;
import ;
import ;
 
import ;
import ;
import ;
import ;
import ;
 
/**
 * @Author yang
 * @Date 2023/1/3 14:15
 * @Version 1.0
 */
@Slf4j
@Component
public class MinioUtil {
    
    /**
     * Minio文件上传
     *
     * @param file       文件实体
     * @param fileName   修饰过的文件名 非源文件名
     * @param bucketName 所存文件夹(桶名)
     * @return
     */
    public ResultEntity<Map<String, Object>> minioUpload(MultipartFile file, String fileName, String bucketName) {
        ResultEntity<Map<String, Object>> resultEntity = new ResultEntity();
        try {
            MinioClient minioClient = ();
            // fileName为空,说明要使用源文件名上传
            if (fileName == null) {
                fileName = ();
                fileName = (" ", "_");
            }
            InputStream inputStream = ();
            PutObjectArgs objectArgs = ().bucket(bucketName).object(fileName)
                    .stream(inputStream, (), -1).contentType(()).build();
            //文件名称相同会覆盖
            (objectArgs);
            return resultEntity;
        } catch (Exception e) {
            ();
            return null;
        }
    }
 
 
    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        try {
            flag = (bucketName);
            if (flag) {
                return true;
            }
        } catch (Exception e) {
            ();
            return false;
        }
        return false;
    }
 
    /**
     * 获取文件流
     *
     * @param fileName   文件名
     * @param bucketName 桶名(文件夹)
     * @return
     */
    public InputStream getFileInputStream(String fileName, String bucketName) {
        try {
            MinioClient minioClient = ();
            return (().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            ();
            (());
        }
        return null;
    }
 
 
    /**
     * @param bucketName:
     * @author
     * @description: 创建桶
     * @date 2022/8/16 14:36
     */
    public void createBucketName(String bucketName) {
        try {
            if ((bucketName)) {
                return;
            }
            MinioClient minioClient = ();
            boolean isExist = (bucketName);
            if (isExist) {
                ("Bucket {} already exists.", bucketName);
            } else {
                (().bucket(bucketName).build());
            }
        } catch (Exception e) {
            ();
            (());
        }
    }
    /**
     * 下载文件
     *
     * @param originalName 文件路径
     */
    public InputStream downloadFile(String bucketName, String originalName, HttpServletResponse response) {
        try {
            MinioClient minioClient = ();
            InputStream file = (().bucket(bucketName).object(originalName).build());
            String filename = new String(("ISO8859-1"), StandardCharsets.UTF_8);
            if ((originalName)) {
                filename = originalName;
            }
            ("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = ();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = (buffer)) > 0) {
                (buffer, 0, len);
            }
            ();
            ();
            ();
            return file;
        } catch (Exception e) {
            ();
            return null;
        }
    }
 
    /**
     * @param bucketName:
     * @description: 删除桶
     * @date 2022/8/16 14:36
     */
    public void deleteBucketName(String bucketName) {
        try {
            if ((bucketName)) {
                return;
            }
            MinioClient minioClient = ();
            boolean isExist = (bucketName);
            if (isExist) {
                (().bucket(bucketName).build());
            }
        } catch (Exception e) {
            ();
            (());
        }
    }
    /**
     * @param bucketName:
     * @description: 删除桶下面所有文件
     * @date 2022/8/16 14:36
     */
    public void deleteBucketFile(String bucketName) {
        try {
            if ((bucketName)) {
                return;
            }
            MinioClient minioClient = ();
            boolean isExist = (().bucket(bucketName).build());
            if (isExist) {
                (().bucket(bucketName).build());
            }
        } catch (Exception e) {
            ();
            (());
        }
    }
 
    /**
     * 根据文件路径得到预览文件绝对地址
     *
     * @param bucketName
     * @param fileName
     * @return
     */
    public String getPreviewFileUrl(String bucketName, String fileName) {
        try {
            MinioClient minioClient = ();
            return (().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            ();
            return "";
        }
    }
}

六、 MinIoController

   文件上传、文件读取、文件下载、文件删除接口如下:

/**
 * @Author yangb
 * @Date 2022/11/27 15:55
 * @Version 1.0
 */
@RestController
@RequestMapping("/minio")
public class MinIoController extends BaseController {
 
    MinioUtil minioUtil = new MinioUtil();
 
    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestBody MultipartFile file) {
        MinioClient minioClient = ();
        if (minioClient == null) {
            return ("连接MinIO服务器失败", null);
        }
        ResultEntity<Map<String, Object>> result = (file, "", "data-enpower");
        if (() == 0) {
            return ("上传成功");
        } else {
            return ("上传错误!!!");
        }
    }
 
    /**
     * 获取文件预览地址
     * @param fileName
     * @return
     */
    @RequestMapping("/getRedFile")
    public AjaxResult getRedFile(@RequestBody String fileName) {
        MinioClient minioClient = ();
        if (minioClient == null) {
            return ("连接MinIO服务器失败", null);
        }
        String url = ("data-enpower",fileName);
        return (url);
    }
 
    /**
     * 下载文件
     * @param fileName
     * @param response
     * @return
     */
    @RequestMapping("/downloadFile")
    public String downloadFile(@RequestParam String fileName, HttpServletResponse response) {
        MinioClient minioClient = ();
        if (minioClient == null) {
            return "连接MinIO服务器失败";
        }
        return ("data-enpower",fileName,response) != null ? "下载成功" : "下载失败";
    }
 
    /**
     * 删除文件
     *
     * @param fileName 文件路径
     * @return
     */
    @PostMapping("/deleteFile")
    public String deleteFile(String fileName) {
        MinioClient minioClient = ();
        if (minioClient == null) {
            return "连接MinIO服务器失败";
        }
        boolean flag = ("data-enpower",fileName);
        return flag == true ? "删除成功" : "删除失败";
    }
 
 
}

七、调试结果

1、 文件上传

minio上的文件

2、 文件下载

3、 文件删除

我们在minio上看看文件是否已删除

原文链接:/Angel_asp/article/details/128535684