MinIO入門學習(三)
阿新 • • 發佈:2020-10-11
Springboot 整合 MinIO
專案通過maven構建首先新增MinIO的maven依賴
<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>3.0.10</version> </dependency>
在resources目錄下建立minio.properties配置檔案,內容如下:
minio.endpoint=http://localhost:9000 minio.accessKey=minioadmin minio.secretKey=minioadmin minio.bucketName=demo
在spring boot專案下建立MinioConfig配置類
使用ConfigurationProperties註解載入指定prefix的值 ,使用@PropertiesSource註解指定的配置檔案,將minio.properties中的配置項載入進來
並建立MinioClient交給spring容器管理
@Data @Component @ConfigurationProperties(prefix = "minio") @PropertySource(value = "classpath:minio.properties") public class MinioConfig { private String endpoint; private int port; private String accessKey; private String secretKey; private String bucketName; @SneakyThrows @Bean public MinioClient getMinioClient() { MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey); return minioClient; } }
建立MinioController,編寫一個上傳檔案的方法
此處的
minioClient.putObject(minioConfig.getBucketName(), objectName, inputStream, MimeTypeUtils.IMAGE_JPEG_VALUE);
後期應寫於sevice層
@RequestMapping("/minio") @RestController public class MinioController { @Autowired private MinioClient minioClient; @Autowired private MinioConfig minioConfig; @PostMapping("upload") public String uploadFile(MultipartFile file) throws IOException { try { String fileName = file.getOriginalFilename(); String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf(".")); InputStream inputStream = file.getInputStream(); minioClient.putObject(minioConfig.getBucketName(), objectName, inputStream, MimeTypeUtils.IMAGE_JPEG_VALUE); } catch (Exception e) { e.printStackTrace(); return "上傳失敗"; } return "上傳成功"; } }