目录
6、minio的基本用法Controlller(上传,下载,预览,删除,查询)
1、配置minio依赖
<minio.version>7.1.0</minio.version>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>${minio.version}</version>
</dependency>
2、配置yml文件
使用那个配置文件就在那个里面配置
minio:
endpoint: http://ip:端口号
accessKey: 用户名
secretKey: 密码
bucketName: 使用的桶名称
3、minio的配置
package com.ruoyi.framework.config;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.InputStream;
@Component
@Data
public class MinioTemplate {
private MinioClient minioClient;
@Value("${minio.endpoint}")
private String endPoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
@Value("${minio.bucketName}")
private String bucketName;
@PostConstruct
public void init(){
minioClient = MinioClient.builder()
.endpoint(endPoint)
.credentials(accessKey,secretKey)
.build();
}
/**文件上传**/
public ObjectWriteResponse uploadFile(String objectName, InputStream inputStream) throws Exception{
return minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(inputStream,-1,10485760).build());
}
/**获取文件流对象**/
public InputStream getFileInputStream(String fileName) throws Exception{
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
}
}
4、minio客户端工具类
package com.ruoyi.common.utils;
import com.ruoyi.common.utils.uuid.IdUtils;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import static com.ruoyi.common.utils.file.FileUploadUtils.getExtension;
/**
* MinIO 客户端工具类
*/
@Component
@Slf4j
public class MinioClientUtils {
@Autowired
private MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
/**
* 检查存储桶是否存在
*
* @param bucketName 存储桶名称
* @return boolean
*/
public boolean bucketExists(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = false;
flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (flag) {
return true;
}
return false;
}
/**
* 创建存储桶
*
* @param bucketName 存储桶名称
*/
public boolean makeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, RegionConflictException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (!flag) {
minioClient.makeBucket(
MakeBucketArgs.builder()
.bucket(bucketName)
.build());
return true;
} else {
return false;
}
}
/**
* 列出所有存储桶名称
*
* @return List<String>
*/
public List<String> listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>();
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}
/**
* 列出所有存储桶
*
* @return List<Bucket>
*/
public List<Bucket> listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
return minioClient.listBuckets();
}
/**
* 删除存储桶
*
* @param bucketName 存储桶名称
* @return boolean
*/
public boolean removeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
// 有对象文件,则删除失败
if (item.size() > 0) {
return false;
}
}
// 删除存储桶,注意,只有存储桶为空时才能删除成功。
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}
/**
* 列出存储桶中的所有对象名称
*
* @param bucketName 存储桶名称
* @return List<String>
*/
public List<String> listObjectNames(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
List<String> listObjectNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
listObjectNames.add(item.objectName());
}
}
return listObjectNames;
}
/**
* 列出存储桶中的所有对象
*
* @param bucketName 存储桶名称
* @return Iterable<Result<Item>>
*/
public Iterable<Result<Item>> listObjects(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
return minioClient.listObjects( ListObjectsArgs.builder().bucket(bucketName).build());
}
return null;
}
/**
* 通过文件上传到对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return boolean
*/
public boolean uploadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucketName).object(objectName).filename(fileName).build());
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 文件上传
*
* @param bucketName 存储捅名称
* @param multipartFile 文件
* @param filename 文件名
*/
public void putObject(String bucketName, MultipartFile multipartFile, String filename) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
putObjectOptions.setContentType(multipartFile.getContentType());
minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(filename).stream(
multipartFile.getInputStream(), multipartFile.getSize(), -1).contentType(multipartFile.getContentType())
.build());
}
/**
* 通过InputStream上传对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param inputStream 要上传的流
* @param contentType 上传的文件类型 例如 video/mp4 image/jpg
* @return boolean
*/
public boolean putObject(String bucketName, String objectName, InputStream inputStream,String contentType) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
//不清楚文件的大小时,可以传-1,10485760。如果知道大小也可以传入size,partsize。
inputStream, -1, 10485760)
.contentType(contentType)
.build());
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 以流的形式获取一个文件对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return InputStream
*/
public InputStream getObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject( GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
return stream;
}
}
return null;
}
/**
* 以流的形式获取一个文件对象(断点下载)
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param offset 起始字节的位置
* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
* @return InputStream
*/
public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject( GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.offset(1024L)
.length(4096L)
.build());
return stream;
}
}
return null;
}
/**
* 下载并将文件保存到本地
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return boolean
*/
public boolean downloadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
minioClient.downloadObject(DownloadObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.filename(fileName)
.build());
return true;
}
}
return false;
}
/**
* 删除一个对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
*/
public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
return true;
}
return false;
}
/**
* 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
*
* @param bucketName 存储桶名称
* @param objectNames 含有要删除的多个object名称的迭代器对象
* @return
* eg:
* List<DeleteObject> objects = new LinkedList<>();
* objects.add(new DeleteObject("my-objectname1"));
* objects.add(new DeleteObject("my-objectname2"));
* objects.add(new DeleteObject("my-objectname3"));
*/
public List<String> removeObjects(String bucketName, List<DeleteObject> objectNames) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNames).build());
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}
/**
* 生成一个给HTTP GET请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws InvalidExpiresRangeException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
throw new InvalidExpiresRangeException(expires,
"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
}
try {
url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.object(objectName)
.expiry(expires)//动态参数
// .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
// .expiry(1, TimeUnit.DAYS)//按天传参
// .expiry(1, TimeUnit.HOURS)//按小时传参数
.build());
} catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidBucketNameException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
e.printStackTrace();
}
}
return url;
}
/**
* 生成一个给HTTP PUT请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return String
*/
public String presignedPutObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
try {
throw new InvalidExpiresRangeException(expires,
"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
} catch (InvalidExpiresRangeException e) {
e.printStackTrace();
}
}
try {
url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(Method.PUT)
.bucket(bucketName)
.object(objectName)
.expiry(expires)//动态参数
// .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
// .expiry(1, TimeUnit.DAYS)//按天传参
// .expiry(1, TimeUnit.HOURS)//按小时传参数
.build());
} catch (ErrorResponseException | InsufficientDataException e) {
e.printStackTrace();
} catch (InternalException e) {
log.error("InternalException",e);
} catch (InvalidBucketNameException e) {
log.error("InvalidBucketNameException",e);
} catch (InvalidExpiresRangeException e) {
log.error("InvalidExpiresRangeException",e);
} catch (InvalidKeyException e) {
log.error("InvalidKeyException",e);
} catch (InvalidResponseException e) {
log.error("InvalidResponseException",e);
} catch (IOException e) {
log.error("IOException",e);
} catch (NoSuchAlgorithmException e) {
log.error("NoSuchAlgorithmException",e);
} catch (ServerException e) {
log.error("ServerException",e);
} catch (XmlParserException e) {
log.error("XmlParserException",e);
}
}
return url;
}
/**
* 获取对象的元数据
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
public ObjectStat statObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = null;
try {
statObject = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (ErrorResponseException e) {
log.error("ErrorResponseException",e);
} catch (InsufficientDataException e) {
log.error("ErrorResponseException",e);
e.printStackTrace();
} catch (InternalException e) {
log.error("InternalException",e);
} catch (InvalidBucketNameException e) {
log.error("InvalidBucketNameException",e);
} catch (InvalidKeyException e) {
log.error("InvalidKeyException",e);
} catch (InvalidResponseException e) {
log.error("InvalidResponseException",e);
} catch (IOException e) {
log.error("IOException",e);
} catch (NoSuchAlgorithmException e) {
log.error("NoSuchAlgorithmException",e);
} catch (ServerException e) {
log.error("ServerException",e);
} catch (XmlParserException e) {
log.error("XmlParserException",e);
}
return statObject;
}
return null;
}
/**
* 文件访问路径
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return String
*/
public String getObjectUrl(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
try {
url = minioClient.getObjectUrl(bucketName, objectName);
} catch (ErrorResponseException e) {
log.error("XmlParserException",e);
} catch (InsufficientDataException e) {
log.error("InsufficientDataException",e);
} catch (InternalException e) {
log.error("InternalException",e);
} catch (InvalidBucketNameException e) {
log.error("InvalidBucketNameException",e);
} catch (InvalidKeyException e) {
log.error("InvalidKeyException",e);
} catch (InvalidResponseException e) {
log.error("InvalidResponseException",e);
} catch (IOException e) {
log.error("IOException",e);
} catch (NoSuchAlgorithmException e) {
log.error("NoSuchAlgorithmException",e);
} catch (ServerException e) {
log.error("ServerException",e);
} catch (XmlParserException e) {
log.error("XmlParserException",e);
}
}
return url;
}
/**
* 编码文件名
*/
public static final String extractFilename(MultipartFile file) {
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
// fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
fileName = IdUtils.fastUUID() + "." + extension;
return fileName;
}
public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
try {
InputStream file = minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build());
String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
if (StringUtils.isNotEmpty(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();
} catch (ErrorResponseException e) {
log.error("ErrorResponseException",e);
} catch (Exception e) {
log.error("Exception",e);
}
}
}
5、minio实体类封装
package com.ruoyi.common.utils.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 该实体主要用于封装用户提交的文件信息表单
*/
@Data
public class MinioResponseDTO {
@ApiModelProperty(value = "文件id")
private String fileId;
@ApiModelProperty(value = "文件访问地址")
private String fileUrl;
@ApiModelProperty(value = "现文件名")
private String originalFileName;
@ApiModelProperty(value = "原文件名")
private String oldFileName;
// @ApiModelProperty("文件")
// private String files;
@ApiModelProperty("base64文件格式")
private String base64Str;
}
6、minio的基本用法Controlller(上传,下载,预览,删除,查询)
package com.ruoyi.web.controller.business;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MinioClientUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.dto.MinioResponseDTO;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.MinioTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
/**
* 培训资料文件存放Controller
*
* @author ruoyi
* @date 2024-05-31
*/
@Slf4j
@RestController
@RequestMapping("/busi/file")
@Api(tags = "minio文件培训资料上传")
public class TbTrainFileController extends BaseController
{
@Autowired
private ITestFileService testFileService;
@Autowired
private MinioTemplate minioTemplate;
@Resource
private MinioClientUtils minioClientUtils;
// @Resource
// private MinioConfig minioConfig;
@PostMapping(value = "/uploadFile")
@ApiOperation(value = "上传文件,支持批量上传")
public AjaxResult uploadFile(@RequestParam("file") List<MultipartFile> files, String trainId) {
// log.info(files.toString());
if (CollectionUtils.isEmpty(files)){
return AjaxResult.error("未选择文件!");
}
List<MinioResponseDTO> MinioResponseDTOList=new ArrayList<>();
for (MultipartFile file : files) {
String originalFilename = file.getOriginalFilename();
// 获取文件拓展名
String extName = FileUtil.extName(originalFilename);
// log.info("文件拓展名:"+extName);
// 生成新的文件名,存入到minio
long millSeconds = Instant.now().toEpochMilli();
String minioFileName=millSeconds+ RandomStringUtils.randomNumeric(12)+"."+extName;
String contentType = file.getContentType();
// log.info("文件mime:{}",contentType);
// 返回文件大小,单位字节
long size = file.getSize();
// log.info("文件大小:"+size);
try {
String bucketName = minioTemplate.getBucketName();
// String bucketName = StringUtils.isNotBlank(file.getModule()) ? body.getModule().replaceAll(",", "") : minIOConfig.getBucketName();
minioClientUtils.putObject(bucketName,file,minioFileName);
String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);
//这里根据自己的表来进行修改
TestFile testFile = new TestFile();
testFile.setId(IdUtils.fastSimpleUUID());
//原文件名称
testFile.setOldFileName(originalFilename);
//文件后缀
testFile.setFileType(extName);
//现文件名成
testFile.setNewFileName(minioFileName);
//文件路径
testFile.setUrl(fileUrl);
//文件大小
// testFile.setFileSize(size);
//文件类型
// testFile.setMime(contentType);
// testFile.setIsDelete(NumberUtils.INTEGER_ZERO);
testFile.setCreateTime(DateUtils.getNowDate());
testFile.setCreateMan(SecurityUtils.getUsername());
// fodminioFile.setIsDelete(NumberUtils.INTEGER_ZERO == 0 ? false : true);
String result = null;
if(extName.equalsIgnoreCase("png") || extName.equalsIgnoreCase("jpg") || extName.equalsIgnoreCase("jpeg")){
byte[] bytes = IoUtil.readBytes(file.getInputStream());
result = Base64.encode(bytes);
result = "data:image/"+extName+";base64,"+result;
}else if(extName.equalsIgnoreCase("mp4")){
byte[] bytes = IoUtil.readBytes(file.getInputStream());
result = Base64.encode(bytes);
result = "data:video/"+extName+";base64,"+result;
}
testFile.setBase64Str(result);
int i = testFileService.insertFile(testFile);
// log.info("添加成功+"+i);
if (i>0) {
MinioResponseDTO minioResponseDTO = new MinioResponseDTO();
//数据库文件id
minioResponseDTO.setFileId(testFile.getId());
//现文件名
minioResponseDTO.setOriginalFileName(minioFileName);
//原文件名
minioResponseDTO.setOldFileName(originalFilename);
minioResponseDTO.setFileUrl(fileUrl);
minioResponseDTO.setBase64Str(result);
MinioResponseDTOList.add(minioResponseDTO);
}
} catch (Exception e) {
log.error("上传文件出错:{}",e);
return AjaxResult.error("上传文件出错");
}
}
return AjaxResult.success(MinioResponseDTOList);
}
@GetMapping("/downloadFile/{fileId}")
@ApiOperation("根据文件id下载文件")
@ApiImplicitParam(name="fileId",value = "文件id",dataType = "String",required = true,paramType = "path")
public void downloadFile(@PathVariable("fileId") String fileId) throws Exception
{
TestFile uploadFiles = testFileService.selectFileById(fileId);
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = requestAttributes.getResponse();
if (StringUtils.isEmpty(uploadFiles.getNewFileName())) {
throw new ServiceException("文件下载失败");
}
InputStream in = minioTemplate.getFileInputStream(uploadFiles.getNewFileName());
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int length = 0;
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(uploadFiles.getNewFileName(), "UTF-8"));
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
out.close();
in.close();
}
@ApiOperation("根据文件id返回文件流")
@ApiImplicitParam(name="fileId",value = "文件id",required = true,paramType = "path",dataType = "string")
@GetMapping("/returnStream/{fileId}")
public void rerurnStream(@PathVariable("fileId") String fileId,HttpServletResponse response) throws IOException {
OutputStream out = null;
ByteArrayOutputStream baos = null;
TestFile uploadFiles = testFileService.selectFileById(fileId);
try {
InputStream in = minioTemplate.getFileInputStream(uploadFiles.getNewFileName());
if (uploadFiles.getNewFileName().endsWith(".doc")) {
// Convert doc to docx
HWPFDocument doc = new HWPFDocument(in);
// new HWPFDocument();
XWPFDocument docxDocument = new XWPFDocument();
Range range = doc.getRange();
for (int i = 0; i < range.numParagraphs(); i++) {
org.apache.poi.hwpf.usermodel.Paragraph paragraph = range.getParagraph(i);
XWPFParagraph docxParagraph = docxDocument.createParagraph();
XWPFRun docxRun = docxParagraph.createRun();
docxRun.setText(paragraph.text());
}
baos = new ByteArrayOutputStream();
docxDocument.write(baos);
}else {
byte[] buffer = new byte[1024];
int len;
baos = new ByteArrayOutputStream();
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
}
out = response.getOutputStream();
out.write(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
baos.flush();
baos.close();
out.flush();
out.close();
}
}
/**
* 删除资料文件存放
*/
@ApiOperation("删除资料文件存放")
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable String[] ids)
{
return toAjax(tbTrainFileService.deleteTbTrainFileByIds(ids));
}
@DeleteMapping("/removeById/{fileId}")
@ApiOperation("根据文件id删除文件")
@ApiImplicitParam(name="fileId",value="文件id",required = true,paramType = "path",dataType = "String")
public AjaxResult removeById(@PathVariable("fileId") String fileId)
{
return toAjax(tbTrainFileService.deleteTbTrainFileById(fileId));
}
/**
* 查询资料文件存放列表
*/
// @PreAuthorize("@ss.hasPermi('system:file:list')")
@ApiOperation("查询资料文件存放列表")
@GetMapping("/list")
public AjaxResult list(TestFile testFile)
{
// startPage();
List<TestFile> list = testFileService.selectFileList(testFile);
return AjaxResult.success(list);
}
}
7、minio文件服务器下载模版
@PostMapping("/exportTemplate")
@ApiOperation("下载自定义基本信息模板")
public void downloadFile() throws Exception {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = requestAttributes.getResponse();
//文件名称要和minio文件服务器里面的文件名称一样
//注意空格
InputStream in = minioTemplate.getFileInputStream("文件名称.xlsx");
if (in == null) {
throw new ServiceException("文件下载失败");
}
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int length = 0;
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode("文件名称.xlsx", "utf-8"));
//通用的二进制数据内容类型
//response.setContentType("application/octet-stream");
//特定的MIME类型,用于标识Microsoft Excel文件
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
out.close();
in.close();
}
到这里,minio的基本配置和用法就完成了
如果有问题可以留言私信,或者评论
有什么建议也可以说一下