Springboot集成Minio实现文件上传下载
概述
minio文档
英文: 中文: 源码: minio-java源码:
集成spring boot
1.导入依赖
<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.2.1</version> </dependency>
2.自定义配置application.yml
oss: #minio地址 server: ${OSS_SERVER:http://ip:9000} #minio存储空间 bucket: ${OSS_BUCKET:xxx} access: # 相当于用户名 key: ${ACCESS_KEY:xxx} secret: # 密码 key: ${SECRET_KEY:xxx}
3.编写工具类
//本模块参照https://github.com/minio/minio-java给的例子进行改动 @Component public class OssFileInterface { @Value("${oss.bucket}") private String bucket; @Value("${oss.server}") private String server; @Value("${oss.access.key}") private String accessKey; @Value("${oss.secret.key}") private String secretKey; public String uploadImage(MultipartFile file) { try { String fileName = file.getOriginalFilename(); String suffixName = ""; if (fileName.contains(".")) { suffixName = fileName.substring(fileName.lastIndexOf(".")); } /* RandomUtil是Hutool的随机串工具类 Hutool官方文档 https://hutool.cn/docs/#/ 依赖如下: <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.5</version> </dependency> */ //生成新的文件名,避免重复 String newFileName = RandomUtil.randomString(5) + System.currentTimeMillis() + suffixName; //创建minio客户端,用于接下来的存储操作,如果你的minio-java依赖版本低,没有builder()方法 MinioClient minioClient = MinioClient.builder().endpoint(server).credentials(accessKey, secretKey).build(); //判断bucket是否存在,没有就创建 boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build()); if (!found) { minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build()); } //上传文件 minioClient.putObject(PutObjectArgs .builder() .bucket(bucket) .object(newFileName) .stream(file.getInputStream(), file.getSize(), -1) .contentType(file.getContentType()) .build()); //返回文件路径 return server + "/" + bucket + "/" + newFileName; } catch (Exception e) { System.out.println("Error occurred: " + e); e.printStackTrace(); } return null; } }
4.编写API
@PostMapping("/file/upload") public String multiUpload(HttpServletRequest request) { MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file"); if (file == null || file.isEmpty()) { return "文件不能为空"; } else { String name = ossFileInterface.uploadImage(file); if (name == null) return "上传失败"; else return "上传成功,文件是" + name; } }
5.测试
使用postman测试
打开http://我的ip:9000/tmp/reqf91628079687948.jpg后跳转到了minio登录界面,这说明bucket没有访问权限。 解决方法: 登录minio web,给bucket配置策略
6.补充
minio web管理页面的功能不全,我们可以使用minio的命令行工具mc进行操作。
我们可以通过docker启动一个实例 docker run -it --entrypoint=/bin/sh minio/mc 连接minio mc alias set minio http://minio的ip:9000 用户名 密码
连接完成后可以建立bucket及更改策略
mc mb minio/bucket名称 mc policy set public minio/bucket名称