一个完整的上传文件示例
一个完整的上传文件示例
需要可以看minio 我的上个文章有介绍
1、加入如下依赖
io.minio minio 8.5.2yaml配置
minio:
endpointUrl: http://127.0.0.1:9000
accessKey: minioadmin
secreKey: minioadmin
bucketName: spzx-bucket
MinioProperties配置类用来通过前缀加载yaml
@Data
@Component
@ConfigurationProperties(prefix = "spzx.minio")
public class MinioProperties {
private String endpointUrl;
private String accessKey;
private String secreKey;
private String bucketName;
}
controller
@Resource
private FileUploadService fileUploadService;
@PostMapping("/fileUpload")
public Result<String> fileUploadService (@RequestParam("file") MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
String url =fileUploadService.uploadFile(file);
return Result.build(url, ResultCodeEnum.SUCCESS);
}
实现类
@Resource
private MinioProperties minioProperties ;
@Override
public String uploadFile(MultipartFile multipartFile) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
try {
// 创建一个Minio的客户端对象
MinioClient minioClient = MinioClient.builder()
.endpoint(minioProperties.getEndpointUrl())
.credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
.build();
// 判断桶是否存在
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
if (!found) { // 如果不存在,那么此时就创建一个新的桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
} else { // 如果存在打印信息
System.out.println("Bucket 'spzx-bucket' already exists.");
}
// 设置存储对象名称
String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
String uuid = UUID.randomUUID().toString().replace("-", "");
//20230801/443e1e772bef482c95be28704bec58a901.jpg
String fileName = dateDir+"/"+uuid+multipartFile.getOriginalFilename();
System.out.println(fileName);
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
.object(fileName)
.build();
minioClient.putObject(putObjectArgs) ;
return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;
} catch (Exception e) {
throw new RuntimeException(e);
}
}