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;
    }
}

测试效果

 

 

猜你喜欢

转载自blog.csdn.net/qq_62646841/article/details/139283155