Minio是一个高性能的对象存储服务器,它可以在Linux、MacOS和Windows等操作系统上运行,并通过命令行界面或RESTful API进行管理。
本文为用Minio存储文件。

1. 在pom.xml文件中添加MinIO的Java客户端库依赖

<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>你的MinIO客户端库版本号</version> </dependency>

2.在application.properties或application.yml中配置MinIO服务器的访问信息

minio:
endpoint: http://your-minio-endpoint
accessKey: your-access-key
secretKey: your-secret-key
bucketName: your-bucket-name

3.创建一个配置类来读取上述配置

@Configuration
public class MinioConfig {

@Value("${minio.endpoint}")
private String endpoint;

@Value("${minio.accessKey}")
private String accessKey;

@Value("${minio.secretKey}")
private String secretKey;

@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}

4.创建文件存储服务和文件下载服务

@Service
public class FileStorageService {

@Autowired
private MinioClient minioClient;

@Value("${minio.bucketName}")
private String bucketName;

public String uploadFile(MultipartFile file) {
try {
// 生成唯一文件名
String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
// 上传到MinIO
minioClient.putObject(bucketName, fileName, file.getInputStream(), file.getSize(),
file.getContentType());
// 返回MinIO中文件的URL
return minioClient.getObjectUrl(bucketName, fileName);
} catch (Exception e) {
throw new RuntimeException("文件上传失败", e);
}
}

public void downloadFile(String objectName, OutputStream outputStream) {
try {
minioClient.getObject(bucketName, objectName, outputStream);
} catch (MinioException e) {
throw new RuntimeException("文件下载失败", e);
}
}
}