Minio 服务器上传文件
1、安装Minio 服务器
2、引入 jar 包
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
需要引入 Hutool jar包
3、接口实现
// 配置信息
// minio 服务器地址
public static final String minioEndpoint = "";
// minio 服务器 用户名
public static final String minioAccessKey = "";
// 密码
public static final String minioSecretKey = "";
// 分支名称 (桶)
public static final String minioBucketName = "";
// 文件上传
@PostMapping("/upload/test")
public String uploadTest(MultipartFile file){
// 文件后缀
String suffix =Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
// 构建文件名称
ThreadLocalRandom random = ThreadLocalRandom.current();
String uuid = new UUID(random.nextLong(), random.nextLong()).toString().replace("-", "");
String fileName = DateUtil.today() + "/" + uuid + suffix;
// minio 客户端
MinioClient client = null;
try {
client = new MinioClient(minioEndpoint, minioAccessKey, minioSecretKey);
if (!client.bucketExists(minioBucketName)) {
client.makeBucket(minioBucketName);
}
try (ByteArrayInputStream stream = IoUtil.toStream(file.getBytes())) {
client.putObject(minioBucketName, fileName, stream, stream.available(), FilePathUtils.getMinorMediaType(fileName));
}
} catch (Exception e) {
e.printStackTrace();
}
return minioBucketName.concat("/").concat(fileName);
}
// 读取文件
@GetMapping("/read")
public ResponseEntity<byte[]> readFile(String namePath) throws Exception {
String bucketName = namePath.split("/")[0];
String fileName = namePath.substring(bucketName.length() + 1);
MinioClient client = new MinioClient(minioEndpoint, minioAccessKey, minioSecretKey);;
InputStream input = client.getObject(bucketName, fileName);
MediaType mediaType = FilePathUtils.getMediaType(namePath);
ResponseEntity.BodyBuilder ok = ResponseEntity.ok().contentType(mediaType);
if (mediaType == MediaType.APPLICATION_OCTET_STREAM) {
//下载 更新文件名称
ok.header(HttpHeaders.CONTENT_DISPOSITION, processFileName(namePath));
}
return ok.body(IoUtil.readBytes(input));
}
// 文件处理类
public class FilePathUtils {
/**
* 获取文件的类型,对应的响应类型
*
* @param namePath 文件名
* @return: org.springframework.http.MediaType
*/
public static MediaType getMediaType(String namePath) {
int i = namePath.lastIndexOf(".") + 1;
String substring = namePath.substring(i);
MediaType mediaType;
switch (substring) {
case "jpg":
mediaType = MediaType.IMAGE_JPEG;
break;
case "png":
mediaType = MediaType.IMAGE_PNG;
break;
case "pdf":
mediaType = MediaType.APPLICATION_PDF;
break;
default:
mediaType = MediaType.APPLICATION_OCTET_STREAM;
break;
}
return mediaType;
}
}