通过从数据库加载MinIO配置并初始化MinioClient,spring boot之Minio上传

发布于:2025-05-18 ⋅ 阅读:(18) ⋅ 点赞:(0)
package org.springblade.modules.resource.endpoint;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.PutObjectArgs;
import io.minio.MinioClient;
import org.springblade.modules.resource.entity.Oss;
import org.springblade.modules.resource.mapper.OssMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class MinioService {



	private String endpoint ;


	private String accessKey ;


	private String secretKey ;
	private String bucketName ;

	private MinioClient minioClient;


	@Resource
	private OssMapper ossMapper;
	/**
	 * 初始化方法:从数据库加载配置并创建 MinioClient
	 */
	@PostConstruct
	public void init() {
		// 从数据库查询配置
		Oss config = ossMapper.selectOne(Wrappers.lambdaQuery(Oss.class)
			.eq(Oss::getOssCode, "minio"));

		if (config == null) {
			throw new RuntimeException("未找到 MinIO 配置!");
		}

		// 赋值配置
		this.endpoint = config.getEndpoint();
		this.accessKey = config.getAccessKey();
		this.secretKey = config.getSecretKey();
		this.bucketName = config.getBucketName();

		// 初始化 MinioClient(仅需创建一次)
		this.minioClient = MinioClient.builder()
			.endpoint(endpoint)
			.credentials(accessKey, secretKey)
			.build();

		// 确保存储桶存在
		try {
			createBucketIfNotExists(bucketName);
		} catch (Exception e) {
			throw new RuntimeException("初始化存储桶失败", e);
		}
	}

	/**
	 * 上传文件到 MinIO
	 */
	public String uploadFile(String name,MultipartFile file) throws Exception {
		// 确保存储桶存在
		createBucketIfNotExists(bucketName);

		// 生成带时间戳的文件名
		String fileName = generateFileNameWithTimestamp(name);

		// 上传文件
		try (InputStream stream = file.getInputStream()) {
			PutObjectArgs args = PutObjectArgs.builder()
				.bucket(bucketName)
				.object(fileName)
				.stream(stream, stream.available(), -1)
				.contentType(file.getContentType())
				.build();

			MinioClient minioClient = new MinioClient.Builder().endpoint(endpoint)
				.credentials(accessKey, secretKey)
				.build();
			minioClient.putObject(args);
			// 拼接 domin+ bucketName + fileName
			String fileLink = endpoint + "/" + bucketName + "/" + fileName;
			return fileLink;
		}
	}

	/**
	 * 生成带时间戳的文件名
	 */
	private String generateFileNameWithTimestamp(String originalFilename) {
		if (originalFilename == null || originalFilename.isEmpty()) {
			return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".unknown";
		}

		String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
		int dotIndex = originalFilename.lastIndexOf('.');

		if (dotIndex > 0) {
			return originalFilename.substring(0, dotIndex) + "_" + timestamp + originalFilename.substring(dotIndex);
		}

		return originalFilename + "_" + timestamp;
	}

	/**
	 * 创建存储桶(如果不存在)
	 */
	private void createBucketIfNotExists(String bucketName) throws Exception {
		boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
		if (!exists) {
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
		}
	}
}

该代码实现了一个基于MinIO的文件上传服务。通过从数据库加载MinIO配置并初始化MinioClient,确保存储桶存在后,可以将文件上传到MinIO服务器。文件上传时,生成带时间戳的文件名,并将文件流上传到指定存储桶。上传成功后,返回文件的访问链接。代码通过@PostConstruct注解在服务初始化时自动加载配置,确保MinioClient的创建和存储桶的检查。整体功能包括文件上传、存储桶管理及文件名生成,适用于需要将文件存储到MinIO的场景。


网站公告

今日签到

点亮在社区的每一天
去签到