Spring Boot + MinIO 实现文件上传
以下是一个使用Spring Boot和MinIO实现文件上传的简单例子:
- 添加MinIO的依赖到
pom.xml
:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>RELEASE_VERSION</version>
</dependency>
将RELEASE_VERSION
替换为当前MinIO客户端库的最新版本。
- 配置MinIO客户端:
@Configuration
public class MinioConfig {
@Value("${minio.url}")
private String url;
@Value("${minio.access-key}")
private String accessKey;
@Value("${minio.secret-key}")
private String secretKey;
@Bean
public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
return new MinioClient(url, accessKey, secretKey);
}
}
在application.properties
或application.yml
中配置MinIO的URL、访问密钥和秘密密钥。
- 创建一个上传文件的服务:
@Service
public class FileUploadService {
private final MinioClient minioClient;
@Autowired
public FileUploadService(MinioClient minioClient) {
this.minioClient = minioClient;
}
public String uploadFile(String bucketName, MultipartFile file) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InternalException, InvalidArgumentException, InvalidResponseException {
String filename = file.getOriginalFilename();
minioClient.putObject(bucketName, filename, file.getInputStream(), file.getContentType());
return filename;
}
}
- 创建一个控制器来处理文件上传的HTTP请求:
@RestController
public class FileUploadController {
private final FileUploadService fileUploadService;
@Autowired
public FileUploadController(FileUploadService fileUploadService) {
this.fileUploadService = fileUploadService;
}
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("bucket") String bucketName) {
try {
String filename = fileUploadService.uploadFile(bucketName, file);
ret
评论已关闭