(springboot整合minio上传文件)

前言

上章讲了MinIo的下载安装及创建bucket方法,今天来讲一下在springboot中如何整合运用MinIo进行文件上传功能。

springboot整合minio

1. 引入minio依赖

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

2. 编写配置文件

minio:
    endpointUrl: http://192.168.200.128:9000
    accessKey: minioadmin
    secreKey: minioadmin
    bucketName: tt-test

3. minio实体类

@Data
@ConfigurationProperties(prefix = "spzx.minio")
public class MinioProperties {
    private String endpointUrl;
    private String accessKey;
    private String secreKey;
    private String bucketName;
}

4. 实现minio配置

public String fileUpload(MultipartFile file) {
        try {
            //创建MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                    .build();
            //创建bucket
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                log.info("Bucket '{}' already exists.", minioProperties.getBucketName());
            }

            //获取文件名称
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String filename = dateDir + "/" + uuid + file.getOriginalFilename();
            //文件上传
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build());
            //获取上传文件在minio的路径
            String url = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + filename;
            log.info("上传图片url:{}", url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.SYSTEM_ERROR, e.getMessage());
        }
    }

5. 实现效果

image.png