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);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了