123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package com.futu.goose.utils;
- import io.minio.*;
- import io.minio.errors.*;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import org.springframework.web.multipart.MultipartFile;
- import java.io.IOException;
- import java.security.InvalidKeyException;
- import java.security.NoSuchAlgorithmException;
- import java.util.UUID;
- @Component
- public class MinioUtils {
- @Value("${minio.endpoint}")
- private String endpoint;
- @Value("${minio.accessKey}")
- private String accessKey;
- @Value("${minio.accessSecret}")
- private String accessSecret;
- @Value("${minio.bucketName}")
- private String bucketName;
- private MinioClient minioClient;
- public MinioUtils() {
- }
- private MinioClient getMinioClient() {
- if (minioClient == null) {
- minioClient = MinioClient.builder()
- .endpoint(endpoint)
- .credentials(accessKey, accessSecret)
- .build();
- }
- return minioClient;
- }
- /**
- * 生成随机文件名
- * @param originalFileName 原始文件名
- * @return 随机文件名
- */
- private String generateRandomFileName(String originalFileName) {
- // 获取文件扩展名
- String extension = "";
- int dotIndex = originalFileName.lastIndexOf('.');
- if (dotIndex > 0) {
- extension = originalFileName.substring(dotIndex);
- }
- // 生成随机 UUID 作为文件名
- String uuid = UUID.randomUUID().toString();
- return uuid + extension;
- }
- /**
- * 上传图片到 MinIO
- * @param file 上传的图片文件
- * @return 图片的访问 URL
- * @throws IOException 输入输出异常
- * @throws ServerException 服务器异常
- * @throws InsufficientDataException 数据不足异常
- * @throws ErrorResponseException 错误响应异常
- * @throws NoSuchAlgorithmException 无此算法异常
- * @throws InvalidKeyException 无效密钥异常
- * @throws InvalidResponseException 无效响应异常
- * @throws XmlParserException XML 解析异常
- * @throws InternalException 内部异常
- */
- public String uploadImage(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, InvalidBucketNameException, RegionConflictException {
- MinioClient client = getMinioClient();
- // 检查存储桶是否存在
- if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
- client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
- }
- // 生成随机文件名
- String objectName = generateRandomFileName(file.getOriginalFilename());
- // 上传文件
- client.putObject(PutObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .stream(file.getInputStream(), file.getSize(), -1)
- .contentType(file.getContentType())
- .build());
- // 返回文件的访问 URL
- return endpoint + "/" + bucketName + "/" + objectName;
- }
- }
|