minio文件上传工具类(springboot)可以直接复制使用

 maven依赖  lombok依赖+minio依赖

    <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.5.2</version>
        </dependency>
        
         <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

 springboot.Yaml配置(默认桶是public)

ydh:
   minio:
     endpointUrl: 你自己网址
     accessKey: 你的登录账号
     secreKey: 你的登录密码
     bucketName: 你自己创建的桶

 minio 配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Data
@Component
@ConfigurationProperties(prefix = "ydh.minio")
public class CloudProperties implements Serializable {


    private String endpointUrl;
    private String accessKey;
    private String secreKey;
    private String bucketName;
}

工具类 (核心代码)

@Component

public class UploadFileUtil {
    private static final Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);

    @Resource
    private CloudProperties minioProperties;

    /**
     * 上传文件到指定目录
     *
     * @param multipartFile 上传的文件
     * @param Dirname       存储到的文件夹名称
     * @return 文件的URL
     */
    public String uploadFile(MultipartFile multipartFile, String Dirname) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, io.minio.errors.ServerException, io.minio.errors.InsufficientDataException {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpointUrl())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                .build();

        // 检查桶是否存在,不存在则创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        } else {
            logger.info("Bucket '{}' already exists.", minioProperties.getBucketName());
        }

        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = Dirname + "/" + uuid + multipartFile.getOriginalFilename();
        logger.info("Uploading file to: {}", fileName);

        // 使用 try-with-resources 确保 InputStream 自动关闭
        try (var inputStream = multipartFile.getInputStream()) {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fileName)
                    .stream(inputStream, multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build();
            minioClient.putObject(putObjectArgs);
        } catch (IOException e) {
            logger.error("Failed to upload file due to IO error: {}", e.getMessage());
            throw e;
        } catch (ServerException | InsufficientDataException | ErrorResponseException | NoSuchAlgorithmException | InvalidKeyException | InvalidResponseException | XmlParserException | InternalException e) {
            logger.error("Failed to upload file due to MinIO error: {}", e.getMessage());
            throw e;
        } catch (RuntimeException e) {
            logger.error("Unexpected error occurred during file upload: {}", e.getMessage());
            throw e;
        }

        String fileUrl = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName;
        logger.info("File uploaded successfully, accessible at: {}", fileUrl);
        return fileUrl;
    }
}

测试效果

 

 

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
你可以使用以下工具类来实现Spring Boot与MinIO结合进行文件分片下载: ```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客户端以及相应的依赖包。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

humannoid

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

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

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

打赏作者

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

抵扣说明:

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

余额充值