1 MinIO
MinIO 是一个基于Apache License v2.0开源协议的对象存储服务。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。
MinIO是一个非常轻量的服务,可以很简单的和其他应用的结合,类似 NodeJS, Redis 或者 MySQL。
2 MinIO安装和启动
由于MinIO是一个单独的服务器,需要单独部署,有关MinIO的使用之前已经总结,有需要可以查看。
3 pom.xml(maven依赖文件)
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.5.7</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>7.0.2</version></dependency>
4 applicatin.properties(配置文件)
# 设置单个文件大小
spring.servlet.multipart.max-file-size= 50MB
#minio文件服务器配置
minio.address=http://localhost:9000
minio.accessKey=admin
minio.secretKey=12345678
minio.bucketName=myfile
5 MinIOService
minio有关的操作(判断存储桶是否存在,创建存储桶,上传文件,下载文件,删除文件)
package com.service;import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;@Data
@Component
public class MinIOService {@Value("${minio.address}")private String address;@Value("${minio.accessKey}")private String accessKey;@Value("${minio.secretKey}")private String secretKey;@Value("${minio.bucketName}")private String bucketName;public MinioClient getMinioClient() {try {return new MinioClient(address, accessKey, secretKey);} catch (Exception e) {e.printStackTrace();return null;}}/*** 检查存储桶是否存在** @param bucketName 存储桶名称* @return*/public boolean bucketExists(MinioClient minioClient, String bucketName) {boolean flag = false;try {flag = minioClient.bucketExists(bucketName);if (flag) {return true;}} catch (Exception e) {e.printStackTrace();return false;}return false;}/*** 创建存储桶** @param bucketName 存储桶名称*/public boolean makeBucket(MinioClient minioClient, String bucketName) {try {boolean flag = bucketExists(minioClient, bucketName);//存储桶不存在则创建存储桶if (!flag) {minioClient.makeBucket(bucketName);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 上传文件** @param file 上传文件* @return 成功则返回文件名,失败返回空*/public String uploadFile(MinioClient minioClient, MultipartFile file) {//创建存储桶boolean createFlag = makeBucket(minioClient, bucketName);//创建存储桶失败if (createFlag == false) {return "";}try {PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);putObjectOptions.setContentType(file.getContentType());String originalFilename = file.getOriginalFilename();int pointIndex = originalFilename.lastIndexOf(".");//得到文件流InputStream inputStream = file.getInputStream();//保证文件不重名(并且没有特殊字符)String fileName = bucketName+ DateUtil.format(new Date(), "_yyyyMMddHHmmss") + (pointIndex > -1 ? originalFilename.substring(pointIndex) : "");minioClient.putObject(bucketName, fileName, inputStream, putObjectOptions);return fileName;} catch (Exception e) {e.printStackTrace();return "";}}/*** 下载文件** @param originalName 文件路径*/public InputStream downloadFile(MinioClient minioClient, String originalName, HttpServletResponse response) {try {InputStream file = minioClient.getObject(bucketName, originalName);String filename = new String(originalName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);if (StrUtil.isNotBlank(originalName)) {filename = originalName;}response.setHeader("Content-Disposition", "attachment;filename=" + filename);ServletOutputStream servletOutputStream = response.getOutputStream();int len;byte[] buffer = new byte[1024];while ((len = file.read(buffer)) > 0) {servletOutputStream.write(buffer, 0, len);}servletOutputStream.flush();file.close();servletOutputStream.close();return file;} catch (Exception e) {e.printStackTrace();return null;}}/*** 删除文件** @param fileName 文件路径* @return*/public boolean deleteFile(MinioClient minioClient, String fileName) {try {minioClient.removeObject(bucketName, fileName);} catch (Exception e) {e.printStackTrace();return false;}return true;}/*** 得到指定文件的InputStream** @param originalName 文件路径* @return*/public InputStream getObject(MinioClient minioClient, String originalName) {try {return minioClient.getObject(bucketName, originalName);} catch (Exception e) {e.printStackTrace();return null;}}/*** 根据文件路径得到预览文件绝对地址** @param minioClient* @param fileName 文件路径* @return*/public String getPreviewFileUrl(MinioClient minioClient, String fileName) {try {return minioClient.presignedGetObject(bucketName,fileName);}catch (Exception e){e.printStackTrace();return "";}}
}
6 FileController
文件上传、文件下载、文件删除接口。
package com.controller;import com.service.MinIOService;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;@RequestMapping("/file")
@RestController
public class FileController {@Autowiredprivate MinIOService minIOService;/*** 上传文件** @param file 文件* @return*/@PostMapping("/uploadFile")public String uploadFile(@RequestBody MultipartFile file) {MinioClient minioClient = minIOService.getMinioClient();if (minioClient == null) {return "连接MinIO服务器失败";}return minIOService.uploadFile(minioClient, file);}/*** 下载文件** @param response 返回请求* @param fileName 文件路径* @return*/@GetMapping("/downloadFile")public String downloadFile(HttpServletResponse response,@RequestParam String fileName) {MinioClient minioClient = minIOService.getMinioClient();if (minioClient == null) {return "连接MinIO服务器失败";}return minIOService.downloadFile(minioClient, fileName, response) != null ? "下载成功" : "下载失败";}/*** 删除文件** @param fileName 文件路径* @return*/@DeleteMapping("/deleteFile/{fileName}")public String deleteFile(@PathVariable("fileName") String fileName) {MinioClient minioClient = minIOService.getMinioClient();if (minioClient == null) {return "连接MinIO服务器失败";}boolean flag = minIOService.deleteFile(minioClient, fileName);return flag == true ? "删除成功" : "删除失败";}
}
7 调试结果
7.1 文件上传
7.2 文件下载
7.3 文件删除
注:
文件删除之后,如果该文件夹下没有文件存在,MinIO会自动删除该空文件夹及上级空文件夹。