Minio快速入门-Java使用篇

部署篇部署完成之后,来到Spring项目中完成文件上传到Minio的功能

1 在Spring项目中配置Minio

引入依赖

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

在application.yaml下配置参数

minio:
  endpoint: http://<hostname>:9000 # 注意上传文件用的是9000端口
  access-key: <access-key>
  secret-key: <secret-key>
  bucket-name: <bucket-name>

创建参数类 

@ConfigurationProperties(prefix = "minio")
@Data
public class MinioProperties {

    private String endpoint;

    private String accessKey;

    private String secretKey;
    
    private String bucketName;
}

创建配置类

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfiguration {

    @Autowired
    private MinioProperties properties;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder().
        endpoint(properties.getEndpoint()).
        credentials(properties.getAccessKey(), properties.getSecretKey()).build();
    }
}

2 使用Minio

定义Controller层

@PostMapping("/upload")
public Result<String> upload(@RequestParam MultipartFile file) throws ServerException, InsufficientDataException,
        ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException,
        XmlParserException, InternalException {
    String url = fileService.upload(file);
    return Result.ok(url);
}

定义Service层

接口

public interface FileService {

    String upload(MultipartFile file) throws ServerException,
            InsufficientDataException, ErrorResponseException,
            IOException, NoSuchAlgorithmException, InvalidKeyException,
            InvalidResponseException, XmlParserException, InternalException;
}

实现类

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private MinioClient client;

    @Resource
    private MinioProperties properties;


    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException,
            NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        // 判断桶是否存在
        boolean bucketExists = client.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
        // 不存在则创建一个新桶
        if (!bucketExists) {
            // 设置桶名
            client.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
            // 设置访问权限
            client.setBucketPolicy(SetBucketPolicyArgs
                    .builder()
                    .bucket(properties.getBucketName()).config(createBucketPolicyConfig(properties.getBucketName())).build());
        }
        // 生成一个日期和UUID拼接原始文件名
        // 防止上传的文件文重复
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
        client.putObject(PutObjectArgs.builder().
                bucket(properties.getBucketName()).
                object(filename).
                stream(file.getInputStream(), file.getSize(), -1).
                contentType(file.getContentType()).build());

        // 返回上传成功的文件名
        return String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);
    }

    private String createBucketPolicyConfig(String bucketName) {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}

3 测试

测试桶存在的情况

上传成功!

测试桶不存在的情况

上传成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值