Spring Boot +Minio 文件上传使用Windows版
minio 下载地址:下载地址
下载之后找到文件找到这个文件
然后打开cmd命令窗口,在这里面输入cmd即可
输入命令运行即可 minio.exe server D:\minio
访问地址:http://127.0.0.1:9000/
账号:minioadmin
密码:minioadmin
登陆进来就可以了
点击右下角+号,选择创建桶,名字随便定义即可
然后找到自己创建的桶,设置可读可写,设置访问权限
点击这个进行编辑
第一个设置为*,第二个选择可读可写
现在开始写代码
第一步导入pom文件
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>3.0.10</version>
</dependency>
第二步创建minio配置文件
@Data
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
/**
* minio 服务地址 http://ip:port
*/
private String url;
/**
* 用户名
*/
private String accessKey;
/**
* 密码
*/
private String secretKey;
/**
* 桶名称
*/
private String bucketName;
}
第二步配置properties文件
minio.url=http://127.0.0.1:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=test
minio:
endpoint: http://127.0.0.1:9000
accesskey: minioadmin
secretKey: minioadmin
bucketName:test
第三步 配置MinioAutoConfiguration
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioAutoConfiguration {
@Autowired
private MinioProperties minioProp;
/**
* 获取 MinioClient
*
* @return
* @throws InvalidPortException
* @throws InvalidEndpointException
*/
@Bean
public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
return new MinioClient(minioProp.getUrl(), minioProp.getAccessKey(), minioProp.getSecretKey());
}
}
第四步 写公共类MinioUtils,我这边只写了上传,crud后面补上
@Slf4j
@Component
public class MinioUtils {
@Autowired
private MinioClient client;
@Autowired
private MinioProperties minioProp;
/**
* 创建bucket
*
* @param bucketName bucket名称
*/
@SneakyThrows
public void createBucket(String bucketName) {
if (!client.bucketExists(bucketName)) {
client.makeBucket(bucketName);
}
}
/**
* 上传文件
*
* @param file 文件
* @param bucketName 存储桶
* @return
*/
public JSONObject uploadFile(MultipartFile file, String bucketName) throws Exception {
JSONObject res = new JSONObject();
res.put("code", 0);
// 判断上传文件是否为空
if (null == file || 0 == file.getSize()) {
res.put("msg", "上传文件不能为空");
return res;
}
// 判断存储桶是否存在
createBucket(bucketName);
// 文件名
String originalFilename = file.getOriginalFilename();
// 新的文件名 = 存储桶名称_时间戳.后缀名
String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
// 开始上传
client.putObject(bucketName,
fileName,
file.getInputStream(),
file.getContentType());
res.put("code", 1);
res.put("msg", minioProp.getUrl() + "/" + bucketName + "/" + fileName);
return res;
}
}
第四步 创建controller
@RestController
@RequestMapping("/test")
public class TesetContrller {
@Autowired
private MinioUtils minioUtils;
@PostMapping("/hello")
public JSONObject test(MultipartFile file){
//桶名
String bucketName="test";
try {
JSONObject jsonObject = minioUtils.uploadFile(file, bucketName);
return jsonObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
第五步 通过postman测试
Content-Type:multipart/form-data
选择文件
这就可以了