Springboot整合Minio实现文件上传和下载

目录

[1. Minio](#1. Minio)

[1.1 Minio下载](#1.1 Minio下载)

[2. Springboot和Minio实现文件存储](#2. Springboot和Minio实现文件存储)


1. Minio

Minio是一个灵活、高性能、开源的对象存储解决方案,适用于各种存储需求,并可以与云计算、容器化、大数据和应用程序集成。它为用户提供了自主控制和可扩展性,使其成为一个强大的存储解决方案。

1.1 Minio下载

安装 MinIO 服务器,从以下 URL 下载 MinIO 可执行文件:

bash 复制代码
https://dl.min.io/server/minio/release/windows-amd64/minio.exe

使用此命令启动下载文件夹中的本地 MinIO 实例。

bash 复制代码
.\minio.exe server C:\minio --console-address :9090

将其输出输出到系统控制台,类似于以下内容:

bash 复制代码
API: http://192.0.2.10:9000  http://127.0.0.1:9000
RootUser: minioadmin
RootPass: minioadmin

Console: http://192.0.2.10:9090 http://127.0.0.1:9090
RootUser: minioadmin
RootPass: minioadmin

Command-line: https://min.io/docs/minio/linux/reference/minio-mc.html
   $ mc alias set myminio http://192.0.2.10:9000 minioadmin minioadmin

Documentation: https://min.io/docs/minio/linux/index.html

WARNING: Detected default credentials 'minioadmin:minioadmin', we recommend that you change these values with 'MINIO_ROOT_USER' and 'MINIO_ROOT_PASSWORD' environment variables.

该过程绑定到当前的 PowerShell 或命令提示符窗口。 关闭窗口将停止服务器并结束进程。

2. Springboot和Minio实现文件存储

pom.xml文件中,添加MinIO的依赖项:

java 复制代码
       <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.2.2</version>
        </dependency>

application.properties文件中,配置MinIO的连接信息:

java 复制代码
minio:
  endpoint: http://127.0.0.1:9000
  accessKey: admin1234
  secretKey: admin1234
  bucketName: bucket1

在Spring Boot的配置类中,创建MinIO的客户端实例:

java 复制代码
@Data
@Configuration
public class MinioConfig {

    /**
     * 访问地址
     */
    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * accessKey类似于用户ID,用于唯一标识你的账户
     */
    @Value("${minio.accessKey}")
    private String accessKey;

    /**
     * secretKey是你账户的密码
     */
    @Value("${minio.secretKey}")
    private String secretKey;

    /**
     * 默认存储桶
     */
    @Value("${minio.bucketName}")
    private String bucketName;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        return minioClient;
    }
}

上传和下载文件:

java 复制代码
@Slf4j
@RestController
@RequestMapping("/oss")
public class OSSController {



    @Autowired
    private MinioConfig minioProperties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (file == null || file.getSize() == 0) {
            log.error("==> 上传文件异常:文件大小为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if(!b){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        }
        String originalFileName = file.getOriginalFilename();
        String contentType = file.getContentType();

        String key = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        String objectName = String.format("%s%s", key, suffix);

        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);
        InputStream inputStream = file.getInputStream();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(contentType)
                .build());

        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
        log.info("==> 上传文件至 Minio 成功,访问路径: {}", url);
        inputStream.close();
        return url;
    }

    @GetMapping("/download")
    public void download(@RequestParam("filename") String filename, HttpServletResponse response) {
        try(InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(filename)
                .build())) {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
        } catch (Exception e) {
            log.error("file download from minio exception, file name: {}", filename,  e);
        }
    }

}

注意:桶权限设置Access Policy为public,否则无法访问图片

相关推荐
世界哪有真情23 分钟前
用虚拟IP扩容端口池:解决高并发WebSocket端口耗尽问题
前端·后端·websocket
知其然亦知其所以然31 分钟前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
武子康34 分钟前
大数据-30 ZooKeeper Java-API 监听节点 创建、删除节点
大数据·后端·zookeeper
知了一笑35 分钟前
SpringBoot3集成多款主流大模型
spring boot·后端·openai
wmze36 分钟前
InnoDB存储引擎--索引与锁
后端
harmful_sheep38 分钟前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵40 分钟前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
调试人生的显微镜41 分钟前
iOS App首次启动请求异常调试:一次冷启动链路抓包与初始化流程修复
后端
大大。42 分钟前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
AI小智1 小时前
Context Engineering:AI 工程的下一个前沿阵地?
后端