此版本为2.0.0,采用spring框架,把MinioFileUtil组件化,配置更加灵活
1.0.0版本链接https://www.yuque.com/r/doc_versions/816772691
结构
config
- MinioConfig
util
- MinioFileUtil
代码
MinioConfig
package com.jili.report.util.file.config;
import io.minio.MinioClient;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* TODO
*
* @author baisongling
* @version 1.0
* @date 2021/6/15 下午5:32
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
private String minioUrl;
private String minioAccessKey;
private String minioSecretKey;
@Bean
@SneakyThrows(Exception.class)
public MinioClient initMinioClient(){
MinioClient minioClient = MinioClient.builder().endpoint(minioUrl).credentials(minioAccessKey,minioSecretKey).build();
return minioClient;
}
}
配置Minio基础信息
MinioFileUtil
package com.jili.report.util.file.util;
import com.jili.report.util.file.config.MinioConfig;
import io.minio.*;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
/**
* TODO
*
* @author liuyujie
* @version 1.0
* @date 2021/2/11 下午5:41
*/
@Component
public class MinioFileUtil {
@Autowired
private MinioConfig minioConfig;
@Autowired
private MinioClient minioClient;
/**
* 判断 bucket是否存在
* @param bucketName
* @return
*/
@SneakyThrows(Exception.class)
public boolean bucketExists(String bucketName) {
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
/**
* 创建 bucket
*
* @param bucketName:
* 桶名
* @return: void
*/
@SneakyThrows(Exception.class)
private void createBucket(String bucketName) {
boolean isExist = bucketExists(bucketName);
if (!isExist) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::"+bucketName+"\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::"+bucketName+"/*\"]}]}";
minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
}
}
/**
* 获取全部bucket
*
* @param :
* @return: java.util.List<io.minio.messages.Bucket>
*/
@SneakyThrows(Exception.class)
public List<Bucket> getAllBuckets() {
return minioClient.listBuckets();
}
/**
* 文件上传
*
* @param bucketName:
* 桶名
* @param fileName:
* 文件名
* @param filePath:
* 文件路径
* @return: void
*/
@SneakyThrows(Exception.class)
public String upload(String bucketName, String fileName, String filePath) {
createBucket(bucketName);
minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketName).object(fileName).filename(filePath).build());
return getFileUrl(bucketName, fileName);
}
/**
* 文件上传
*
* @param bucketName:
* 桶名
* @param fileName:
* 文件名
* @param stream:
* 文件流
* @return: java.lang.String : 文件url地址
*/
@SneakyThrows(Exception.class)
public String upload(String bucketName, String fileName, InputStream stream) {
createBucket(bucketName);
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(stream, stream.available(), -1).contentType("application/octet-stream").build());
// minioClient.putObject(bucketName,fileName,stream,"application/octet-stream");
return getFileUrl(bucketName, fileName);
}
/**
* 文件上传
*
* @param bucketName:
* 桶名
* @param file:
* 文件
* @return: 文件url地址
*/
@SneakyThrows(Exception.class)
public String upload(String bucketName, MultipartFile file) {
createBucket(bucketName);
final InputStream is = file.getInputStream();
final String originalFilename = file.getOriginalFilename();
String fileName = bucketName + "_" +
System.currentTimeMillis() +
originalFilename.substring(originalFilename.lastIndexOf("."));
String url = upload(bucketName,fileName,is);
is.close();
return url;
}
/**
* fileName作为参数传进来,解耦,便于自定义路径以及URI
* @param file
* @param bucketName
* @param fileName
* @return
*/
@SneakyThrows(Exception.class)
public String upload(MultipartFile file, String bucketName, String fileName) {
createBucket(bucketName);
final InputStream is = file.getInputStream();
String url = upload(bucketName,fileName,is);
is.close();
return url;
}
/**
* 删除文件
*
* @param bucketName:
* 桶名
* @param fileName:
* 文件名
* @return: void
*/
@SneakyThrows(Exception.class)
public void deleteFile(String bucketName, String fileName) {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
}
/**
* 获取文件
* @param bucketName
* @param fileName
* @return
*/
@SneakyThrows(Exception.class)
private InputStream getObject(String bucketName, String fileName){
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
}
/**
* 下载文件
*
* @param bucketName:
* 桶名
* @param fileName:
* 文件名
* @param response:
* @return: void
*/
@SneakyThrows(Exception.class)
public ResponseEntity download(String bucketName, String fileName, HttpServletResponse response) {
ResponseEntity<byte[]> responseEntity = null;
InputStream stream = null;
ByteArrayOutputStream output = null;
try {
stream = getObject(bucketName, fileName);
if (stream == null) {
System.out.println("文件不存在");
}
//用于转换byte
output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = stream.read(buffer))) {
output.write(buffer, 0, n);
}
byte[] bytes = output.toByteArray();
//设置header
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Accept-Ranges", "bytes");
httpHeaders.add("Content-Length", bytes.length + "");
httpHeaders.add("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
httpHeaders.add("Content-Type", "text/plain;charset=utf-8");
responseEntity = new ResponseEntity<byte[]>(bytes, httpHeaders, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
stream.close();
}
if (output != null) {
output.close();
}
}
return responseEntity;
}
/**
* 获取minio文件的下载地址
*
* @param bucketName:
* 桶名
* @param fileName:
* 完整文件名
* @return: url
*/
@SneakyThrows(Exception.class)
public String getFileUrl(String bucketName, String fileName) {
return minioConfig.getMinioUrl()+"/"+bucketName+"/"+fileName;
}
}
Minio文件管理实现方法
yml
minio:
minioUrl:
minioAccessKey:
minioSecretKey:
案例
@PostMapping("/upload")
public String upload(MultipartFile file){
if (file.isEmpty() || file.getSize() == 0) {
return "文件为空";
}
String fileName = file.getOriginalFilename();
String newName = "img/"+ UUID.randomUUID().toString().replaceAll("-", "")+ fileName.substring(fileName.lastIndexOf("."));
return minioFileUtil.upload(file,"test",newName);
}