springboot minio 工具类,一站式解决

注意

minio 新版本有9000和9090两个端口,web访问是9000,但走api上传和访问都是9090端口

引入pom

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

controller

 @PostMapping("uploadMinio")
    public static String uploadMinio(@RequestParam("file") MultipartFile multipartFile){
        try{
           return MinioUtil.upload(multipartFile);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
MinioUtil
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

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

public class MinioUtil {

    // 替换为你的MinIO服务器地址、端口、访问密钥和秘密密钥
    private static final String endpoint = "http://localhost:9090";
    private static final String accessKey = "xxx";
    private static final String secretKey = "xxx";
    private static final String bucketName = "xxx";
    private static final String host = "http://localhost:9090/" + bucketName + "/";

    public static String upload(MultipartFile multipartFile) throws IOException {
        InputStream inputStream = null;

        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();


            // 获取文件后缀
            String suffix = getFileExtension(multipartFile.getOriginalFilename());
            if (StringUtils.isBlank(suffix)) {
                return "";
            }

            // 修改 objectName 为正确的文件名 + 后缀
            String objectName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

            inputStream = convertMultipartFileToInputStream(multipartFile);

            // 检查存储桶是否存在,如果不存在则创建
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, multipartFile.getSize(), -1)
                            .contentType("application/octet-stream") // 设置文件类型
                            .build());

            return host + objectName; // 返回上传后的对象名
        } catch (IOException | XmlParserException | ServerException | NoSuchAlgorithmException |
                InsufficientDataException | InvalidKeyException | InvalidResponseException |
                ErrorResponseException | InternalException e) {
            return null;
        } finally {
            inputStream.close();
        }
    }

    public static String getFileExtension(String filePath) {
        int lastDotIndex = filePath.lastIndexOf(".");
        if (lastDotIndex > 0) {
            return filePath.substring(lastDotIndex + 1);
        }
        return ""; // 如果找不到点或没有后缀,则返回空字符串
    }

    public static InputStream convertMultipartFileToInputStream(MultipartFile multipartFile) throws IOException {
        return multipartFile.getInputStream();
    }
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用以下工具类来实现Spring BootMinIO结合进行文件分片下载: ```java import io.minio.MinioClient; import io.minio.ObjectStat; import io.minio.errors.*; import io.minio.messages.Part; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.List; @Component public class MinioFileDownloader { @Autowired private MinioClient minioClient; public void downloadFile(String bucketName, String objectName, String filePath) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InsufficientDataException, InternalException, InvalidResponseException, ErrorResponseException, XmlParserException, InvalidArgumentException { // 获取文件的元数据 ObjectStat objectStat = minioClient.statObject(bucketName, objectName); long fileSize = objectStat.length(); if (fileSize <= 0) { throw new IOException("File is empty"); } // 分片下载文件 int partSize = 5 * 1024 * 1024; // 分片大小为5MB long totalPartsCount = (long) Math.ceil((double) fileSize / partSize); for (int partNumber = 1; partNumber <= totalPartsCount; partNumber++) { long offset = (partNumber - 1) * partSize; long size = Math.min(partSize, fileSize - offset); InputStream inputStream = minioClient.getObject(bucketName, objectName, offset, size); try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) { byte[] buffer = new byte[(int) size]; bufferedInputStream.read(buffer, 0, (int) size); // 将分片写入文件 writeToFile(buffer, filePath); } } } private void writeToFile(byte[] data, String filePath) throws IOException { try (FileOutputStream outputStream = new FileOutputStream(filePath, true)) { outputStream.write(data); } } } ``` 你可以将以上代码添加到你的Spring Boot项目,然后通过注入`MinioClient`来使用`MinioFileDownloader`类进行文件的分片下载。请确保已经正确配置了MinIO客户端以及相应的依赖包。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值