🍁 作者:知识浅谈,CSDN签约讲师,CSDN博客专家,华为云云享专家,阿里云专家博主 📌 擅长领域:全栈工程师、爬虫、ACM算法 🔥 公众号:知识浅谈

(🤞SpringBoot项目整合MinIO实现文件的上传下载🤞)

🎈前言

在Spring Boot项目中整合MinIO以实现文件的上传、下载和获取文件路径的功能,可以通过以下步骤进行。MinIO是一个高性能的分布式对象存储服务,用于存储非结构化数据如图片、视频等。

🎈部署实现

🍮安装MinIO

首先,你需要在本地或服务器上安装MinIO。这里假设你已经安装好了MinIO,并且它正在运行。

🍮创建Spring Boot项目

使用Spring Initializr 创建一个新的Spring Boot项目。 添加依赖:在pom.xml中添加MinIO客户端依赖。

<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.4.6</version>
</dependency>

同时,确保添加了Spring Boot Web依赖,以便创建RESTful API。

🍮配置MinIO连接信息

在application.properties或application.yml文件中配置MinIO的连接信息。

# application.properties
minio.url=http://localhost:9000
minio.accessKey=your-access-key
minio.secretKey=your-secret-key
minio.bucketName=your-bucket-name

🍮编写配置类

创建一个配置类来初始化MinIO客户端。

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.url}")
    private String url;

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

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

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

🍮编写服务类

在服务类中实现文件的上传、下载和获取文件路径的方法。

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.GetObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

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

    public String uploadFile(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());
        return "http://" + minioClient.getEndpoint().getHostName() + ":" + minioClient.getEndpoint().getPort() + "/" + bucketName + "/" + fileName;
    }

    public InputStream downloadFile(String fileName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build());
    }

    // 注意:MinIO本身不直接提供“获取文件路径”的功能,因为存储的是对象,不是文件系统路径
    // 这里的“获取文件路径”实际上是返回可以访问该文件的URL
}

🍮编写控制器类

创建一个控制器类来处理文件上传和下载的HTTP请求。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

    @Autowired
    private MinioService minioService;

    @PostMapping("/upload")
    public```java
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
    try {
        String fileUrl = minioService.uploadFile(file);
        return ResponseEntity.ok(fileUrl);
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file: " + e.getMessage());
    }
}

@GetMapping("/download/{fileName}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
    try (InputStream inputStream = minioService.downloadFile(fileName)) {
        byte[] fileContent = inputStream.readAllBytes(); // 注意:对于大文件,这可能会导致内存溢出
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }
}

🍮运行和测试

启动Spring Boot应用:确保你的Spring Boot应用已经正确启动。 测试文件上传:使用Postman或任何其他API测试工具发送一个包含文件的POST请求到/api/files/upload。 测试文件下载:发送一个GET请求到/api/files/download/{fileName},其中{fileName}是你上传的文件名。

🍚总结

大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。 作者:知识浅谈