Spring Boot + MinIO 实现文件上传

这段时间一直在忙学校毕业答辩的事情。感觉好久没发博客了,在校期间接触到了MinIO 这个东东。答辩完赶紧记录下来。

MinIO 概念:

MinIO是一个开源的对象存储服务器软件,它是基于云原生架构设计的。MinIO允许用户使用标准的HTTP/REST接口来存储和检索任意类型的数据,包括照片、视频、文档等。它支持分布式部署,可以通过水平扩展来实现高可用性和高性能。
换一个方式说:
比如说,想象一下你家里有一个超大的仓库,里面可以存放各种东西,比如衣服、书籍、家具等等。这个仓库就好像是 MinIO,它能够以高效率和可靠性地存储你的各种物品,而且你可以根据需要随时拿出来或者放进去。这样,你就可以方便地组织和管理你的物品,就像使用 MinIO 来管理你的数据一样。

文件切片上传简介:

文件切片上传是指将大文件分割成小的片段,然后通过多个请求并行上传这些片段,最终在服务器端将这些片段合并还原为完整的文件。这种方式有助于规避一些上传过程中的问题,如网络不稳定、上传中断等,并能提高上传速度。

技术选型

Spring Boot

Spring Boot是一个基于Spring框架的轻量级、快速开发的框架,提供了许多开箱即用的功能,适合构建现代化的Java应用。

MinIO

MinIO是一款开源的对象存储服务器,与Amazon S3兼容。它提供了高性能、高可用性的存储服务,适用于大规模文件存储。

在这里插入图片描述

搭建Spring Boot项目

首先,我们需要搭建一个基本的Spring Boot项目。可以使用Spring Initializer(https://start.spring.io/)生成项目骨架,选择相应的依赖,如Web和Thymeleaf

<!-- pom.xml -->

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Thymeleaf模板引擎 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- MinIO Java客户端 -->
    <dependency>
        <groupId>io.minio</groupId>
        <artifactId>minio</artifactId>
        <version>8.3.3</version>
    </dependency>
</dependencies>

集成MinIO

配置MinIO连接信息

在application.properties中配置MinIO的连接信息,包括服务地址、Access Key和Secret Key。

# application.properties

# MinIO配置
minio.endpoint=http://localhost:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=mybucket

MinIO配置类

创建MinIO配置类,用于初始化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.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();
    }
}

文件切片上传实现

控制器层

创建一个文件上传的控制器,负责处理文件切片上传的请求。

import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

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

    @Autowired
    private MinioClient minioClient;

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

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        // 实现文件切片上传逻辑
        // ...

        return "Upload success!";
    }
}

服务层

创建文件上传服务类,处理文件切片的具体上传逻辑。

import io.minio.MinioClient;
import io.minio.errors.*;
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.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileService {

    @Autowired
    private MinioClient minioClient;

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

    public void uploadFile(String objectName, MultipartFile file) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, InvalidBucketNameException, XmlParserException, InvalidArgumentException {
        // 实现文件切片上传逻辑
        // ...
    }
}

文件切片上传逻辑

在服务层的uploadFile方法中实现文件切片上传逻辑。这里使用MinIO的putObject方法将文件切片上传至MinIO服务器。

import io.minio.PutObjectArgs;
import io.minio.errors.*;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class FileService {

    // 省略其他代码...

    public void uploadFile(String objectName, MultipartFile file) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, InvalidBucketNameException, XmlParserException, InvalidArgumentException {
        InputStream inputStream = file.getInputStream();
        long size = file.getSize();
        long chunkSize = 5 * 1024 * 1024; // 每片大小5MB

        long offset = 0;
        while (offset < size) {
            long currentChunkSize = Math.min(chunkSize, size - offset);
            byte[] chunk = new byte[(int) currentChunkSize];
            inputStream.read(chunk);

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, currentChunkSize, -1)
                            .build()
            );

            offset += currentChunkSize;
        }

        inputStream.close();
    }
}

文件合并逻辑

在文件上传完成后,需要将所有的切片文件合并还原为完整的文件。在FileController中增加一个合并文件的接口。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

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

    // 省略其他代码...

    @Autowired
    private FileService fileService;

    @PostMapping("/merge")
    public String merge(@RequestParam String objectName) {
        try {
            fileService.mergeFile(objectName);
            return "Merge success!";
        } catch (Exception e) {
            e.printStackTrace();
            return "Merge failed!";
        }
    }
}

在FileService中增加合并文件的方法。

import io.minio.CopyObjectArgs;
import io.minio.GetObjectArgs;
import io.minio.PutObjectArgs;
import io.minio.errors.*;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class FileService {

    // 省略其他代码...

    public void mergeFile(String objectName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, InvalidBucketNameException, XmlParserException, InvalidArgumentException {
        Iterable<io.minio.messages.Item> parts = minioClient.listObjects(bucketName, objectName);

        // 通过CopyObject将所有分片合并成一个对象
        for (io.minio.messages.Item part : parts) {
            String partName = part.objectName();
            minioClient.copyObject(
                    CopyObjectArgs.builder()
                            .source(bucketName, partName)
                            .destination(bucketName, objectName)
                            .build()
            );
        }

        // 删除所有分片
        for (io.minio.messages.Item part : parts) {
            String partName = part.objectName();
            minioClient.removeObject(bucketName, partName);
        }
    }
}

页面展示

在前端页面,使用Thymeleaf模板引擎展示上传按钮和上传进度。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <form id="uploadForm" action="/file/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="file" />
        <input type="submit" value="Upload" />
    </form>

    <div id="progress" style="display: none;">
        <progress id="progressBar" max="100" value="0"></progress>
        <span id="percentage">0%</span>
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', function (event) {
            event.preventDefault();

            var fileInput = document.getElementById('file');
            var file = fileInput.files[0];
            if (!file) {
                alert('Please choose a file.');
                return;
            }

            var formData = new FormData();
            formData.append('file', file);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/file/upload', true);

            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    var percentage = Math.round((e.loaded / e.total) * 100);
                    document.getElementById('progressBar').value = percentage;
                    document.getElementById('percentage').innerText = percentage + '%';
                }
            };

            xhr.onload = function () {
                document.getElementById('progress').style.display = 'none';
                alert('Upload success!');
            };

            xhr.onerror = function () {
                alert('Upload failed!');
            };

            xhr.send(formData);

            document.getElementById('progress').style.display = 'block';
        });
    </script>
</body>
</html>

性能优化与拓展

性能优化

并发上传: 利用多线程或异步任务,将文件切片并行上传,提高上传效率。
分布式部署: 将文件存储和应用部署在不同的服务器,减轻单个服务器的负担,提高整体性能。

拓展功能

断点续传: 支持文件上传中断后的断点续传功能,提高用户体验。
权限控制: 使用MinIO的访问策略进行权限控制,确保文件上传安全性。

总结

通过本文,我们深入了解了如何使用Spring Boot和MinIO实现文件切片上传技术。通过文件切片上传,我们能够提高文件上传的速度,优化用户体验。在实际应用中,我们可以根据需求进行性能优化和功能拓展,使得文件上传系统更加强大和可靠。希望本文对您理解文件切片上传技术以及Spring Boot和MinIO的使用有所帮助。

  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Minio Java客户端来实现Spring BootMinio的集成,下面是一个基本的步骤: 1.引入Minio Java客户端的依赖: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>7.0.2</version> </dependency> ``` 2.配置Minio的连接信息: ``` @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() throws Exception { return new MinioClient(url, accessKey, secretKey); } } ``` 其中minio.url是Minio服务器的地址,minio.accessKey和minio.secretKey是访问Minio服务器所需的密钥信息。 3.编写文件上传接口: ``` @RestController public class FileUploadController { @Autowired private MinioClient minioClient; @PostMapping("/upload") // 访问路径 public String upload(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); minioClient.putObject("bucketName", fileName, inputStream, file.getContentType()); return "上传成功"; } catch (Exception e) { e.printStackTrace(); return "上传失败"; } } } ``` 其中minioClient.putObject()方法的参数解释如下: - bucketName:存储桶的名称,如果不存在则会自动创建 - fileName:文件在存储桶中的名称 - inputStream:文件的输入流 - contentType:文件类型,如text/plain、image/jpeg等 4.测试上传接口: 启动Spring Boot应用,并使用Postman等工具测试上传接口,文件上传成功后会在Minio服务器中创建一个存储桶,并且文件会存储在其中。 以上就是Spring Boot集成Minio实现文件批量上传的过程,希望对你有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱写Bug的小孙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值