使用SpringBoot集成Minio实现文件上传、下载、删除功能

1. 添加依赖

首先,在你的Spring Boot项目中添加Minio的依赖。在 pom.xml 文件中添加以下依赖:

XML 复制代码
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>你的版本</version>
</dependency>

2. 配置application.properties

application.properties 中配置Minio连接信息:

XML 复制代码
# Minio文件服务配置
minio:
  # 访问服务地址
  url: "http://127.0.0.1:5000"
  # 用户名
  user-name: "madmin"
  # mi码
  password: "madmin"
  # 桶的名称
  bucket-name: "test"

3. 创建Minio配置类

创建一个配置类 MinioConfig.java,用于初始化Minio客户端:

java 复制代码
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

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

4. 实现文件上传、下载、删除操作

创建一个服务类 MinioFileService.java,实现文件上传、下载、删除等操作:

java 复制代码
import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MinioFileService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    // 上传文件
    public String uploadFile(MultipartFile file) throws IOException {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try (InputStream inputStream = file.getInputStream()) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(inputStream, inputStream.available(), -1)
                            .contentType(file.getContentType())
                            .build());
        } catch (MinioException | IOException e) {
            throw new IOException("File upload failed: " + e.getMessage());
        }
        return fileName;
    }

    // 下载文件
    public InputStream downloadFile(String fileName) throws IOException {
        try {
            return minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build());
        } catch (MinioException e) {
            throw new IOException("File download failed: " + e.getMessage());
        }
    }

    // 删除文件
    public void deleteFile(String fileName) throws IOException {
        try {
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build());
        } catch (MinioException e) {
            throw new IOException("File deletion failed: " + e.getMessage());
        }
    }

    // 获取所有文件列表
    public List<String> getAllFiles() throws IOException {
        try {
            return minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(bucketName)
                            .build())
                    .stream()
                    .map(Result::get)
                    .map(Item::objectName)
                    .collect(Collectors.toList());
        } catch (MinioException e) {
            throw new IOException("Failed to retrieve file list: " + e.getMessage());
        }
    }
}

5. 创建Controller层接口

创建一个Controller类 FileController.java,定义REST接口,实现文件上传、下载、删除的调用:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private MinioFileService minioFileService;

    // 文件上传
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        return minioFileService.uploadFile(file);
    }

    // 文件下载
    @GetMapping("/download/{fileName:.+}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        InputStream is = minioFileService.downloadFile(fileName);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    }

    // 文件删除
    @DeleteMapping("/delete/{fileName:.+}")
    public void deleteFile(@PathVariable String fileName) throws IOException {
        minioFileService.deleteFile(fileName);
    }

    // 获取所有文件列表
    @GetMapping("/list")
    public List<String> getAllFiles() throws IOException {
        return minioFileService.getAllFiles();
    }
}

6. 测试接口

启动Spring Boot应用程序,使用Postman或浏览器访问接口测试文件上传、下载、删除功能。

这样,你就完成了Spring Boot与Minio的集成,实现了基本的文件上传、下载、删除操作。

相关推荐
Full Stack Developme8 分钟前
java.net 包详解
java·python·.net
一叶飘零_sweeeet26 分钟前
深入 Spring 内核:解密 15 种设计模式的实战应用与底层实现
java·spring·设计模式
凤山老林31 分钟前
排序算法:详解插入排序
java·开发语言·后端·算法·排序算法
洛克大航海33 分钟前
3-SpringCloud-LoadBalancer-OpenFeign服务调用与负载均衡
spring·spring cloud·负载均衡·openfeign·loadbalancer
彦楠34 分钟前
IDEA实用快捷键
java·ide·intellij-idea
豆沙沙包?42 分钟前
2025年--Lc197-077. 排序链表(链表,尾插法)--Java版
java·数据结构·链表
m0_651593911 小时前
深入理解软件设计中的协议与规范:从理论到Java实践
java·软件工程·代码规范·设计规范
低音钢琴1 小时前
【SpringBoot从初学者到专家的成长18】SpringBoot中的数据持久化:JPA与Hibernate的结合
spring boot·后端·hibernate
paopaokaka_luck1 小时前
基于SpringBoot+Vue的社区诊所管理系统(AI问答、webSocket实时聊天、Echarts图形化分析)
vue.js·人工智能·spring boot·后端·websocket
Knight_AL1 小时前
Tomcat 类加载器隔离机制的实际应用
java·tomcat