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
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

humannoid

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

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

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

打赏作者

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

抵扣说明:

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

余额充值