minio操作工具类(其中,ip,端口,账号,密码在配置文件中配置)
@Api(value = "minio操作")
@Component
public class UploadFileToMinio implements InitializingBean {
@Value("${minio.endpoint}")
private String endpoint;//minio ip
@Value("${minio.port}")
private int port;//minio 端口
@Value("${minio.accessKey}")
private String accessKey;//minio 账号
@Value("${minio.secretKey}")
private String secretKey;//minio 密码
@Value("${minio.secure}")
private boolean secure;//如果是true,则用的是https而不是http,默认值是true
public MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
@Override
public void afterPropertiesSet() throws Exception {
minioClient = new MinioClient(endpoint, port, accessKey, secretKey,secure);
}
/**
* 检查存储桶是否存在
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean bucketExists(String bucketName) {
boolean flag = false;
flag = minioClient.bucketExists(bucketName);
if (flag) {
return true;
}
return false;
}
/**
* 创建存储桶
*
* @param bucketName 存储桶名称
*/
@SneakyThrows
public boolean makeBucket(String bucketName) {
boolean flag = bucketExists(bucketName);
if (!flag) {
minioClient.makeBucket(bucketName);
return true;
} else {
return false;
}
}
/**
* 列出所有存储桶名称
*
* @return
*/
@SneakyThrows
public List<String> listBucketNames() {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>();
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}
/**
* 列出所有存储桶
*
* @return
*/
@SneakyThrows
public List<Bucket> listBuckets() {
return minioClient.listBuckets();
}
/**
* 删除存储桶
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean removeBucket(String bucketName) {
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(bucketName);
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}
/**
* 列出存储桶中的所有对象名称
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public List<String> listObjectNames(String bucketName) {
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
*/
@SneakyThrows
public Iterable<Result<Item>> listObjects(String bucketName) {
boolean flag = bucketExists(bucketName);
if (flag) {
return minioClient.listObjects(bucketName);
}
return null;
}
/**
* 通过文件上传到对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, String fileName) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(bucketName, objectName, fileName, null);
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 文件上传
*
* @param bucketName
* @param multipartFile
*/
@SneakyThrows
public void putObject(String bucketName, MultipartFile multipartFile, String filename) {
PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
putObjectOptions.setContentType(multipartFile.getContentType());
minioClient.putObject(bucketName, filename, multipartFile.getInputStream(), putObjectOptions);
}
/**
* 通过InputStream上传对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param stream 要上传的流
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, InputStream stream) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 以流的形式获取一个文件对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(bucketName, objectName);
return stream;
}
}
return null;
}
/**
* 以流的形式获取一个文件对象(断点下载)
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param offset 起始字节的位置
* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(bucketName, objectName, offset, length);
return stream;
}
}
return null;
}
/**
* 下载并将文件保存到本地
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
*/
@SneakyThrows
public boolean getObject(String bucketName, String objectName, String fileName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
minioClient.getObject(bucketName, objectName, fileName);
return true;
}
}
return false;
}
/**
* 删除一个对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
*/
@SneakyThrows
public boolean removeObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(bucketName, objectName);
return true;
}
return false;
}
/**
* 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
*
* @param bucketName 存储桶名称
* @param objectNames 含有要删除的多个object名称的迭代器对象
* @return
*/
@SneakyThrows
public List<String> removeObject(String bucketName, List<String> objectNames) {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
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
*/
@SneakyThrows
public String presignedGetObject(String bucketName, String objectName, Integer expires) {
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);
}
url = minioClient.presignedGetObject(bucketName, objectName, expires);
}
return url;
}
/**
* 生成一个给HTTP PUT请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
@SneakyThrows
public String presignedPutObject(String bucketName, String objectName, Integer expires) {
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);
}
url = minioClient.presignedPutObject(bucketName, objectName, expires);
}
return url;
}
/**
* 获取对象的元数据
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public ObjectStat statObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = minioClient.statObject(bucketName, objectName);
return statObject;
}
return null;
}
/**
* 文件访问路径
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public String getObjectUrl(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
url = minioClient.getObjectUrl(bucketName, objectName);
}
return url;
}
public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
try {
InputStream file = minioClient.getObject(bucketName, fileName);
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) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
借助工具类实现minio中文件的上传下载,其中上传很简单直接调上面的方法就好了,但是下载有问题的,要求是在浏览器下载,也就是后端传流给前端,由前端下载但是问题是minio中文件存的格式不固定,什么exe,text啥的都有,这就导致前端设置的文件类型如果和minio中的文件类型不一致,下载的文件就会打不开损坏,
我的思路是将下载下来的文件存到本地再打成压缩包发给前端,前端设置格式为.zip的压缩文件,这样不管存的啥文件下载下来都是压缩包,解压后就能得到源文件了,代码如下
其中xxxx是我们项目中的实体类,换成你的实体就好了,要可以根据这个实体获取到minio的桶名,文件名等信息
@PostMapping("/downloadFile")
public ResultEntity downloadFile(HttpServletResponse response ,@RequestBody XXXX xxxx) {
response.setContentType("application/zip");
try {
InputStream object = uploadFileToMinio.getObject(xxxx.getBucketName(), xxxx.getFileName());
//根据当前类 获取项目路径
String realAppPath = DataBackServiceImpl.class.getResource("/").toString();
int index = realAppPath.indexOf("target");
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
int var = 1;
if (os.startsWith("Win") || os.startsWith("win"))
var = 0;
realAppPath = realAppPath.substring(6 - var, index - 1); // ***/appsec
// 创建临时存储文件目录
File file1 = new File(realAppPath + "/minio-Temp");
if (!file1.exists()) {
file1.mkdir();
}
// 创建压缩文件
String zipSavePath = realAppPath + "/minio-Temp/test.zip";
ZipFile zipFile = new ZipFile(zipSavePath);
//创建临时存储文件
//获取文件后缀
String fileName = xxxx.getFileName();
String[] split = fileName.split("\\.");
String s = split[split.length - 1];
File file = new File(realAppPath + "/minio-Temp/firmware." + s);
if (!file.exists()) {
file.createNewFile();
}
//保存文件的方法
this.saveFile(object,realAppPath,s);
//设置压缩参数
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.addFile(new File(realAppPath+ "/minio-Temp/firmware."+s),parameters);
File zipFile1 = new File(zipSavePath);
InputStream input = new FileInputStream(zipFile1);
OutputStream outputStream1 = response.getOutputStream();
byte[] buf = new byte[1024*10];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
outputStream1.write(buf, 0, bytesRead);
}
input.close();
object.close();
outputStream1.close();
// 删除临时文件
this.deleteDir(file1);
} catch (IOException e) {
e.printStackTrace();
}catch (ZipException e) {
e.printStackTrace();
}
return null;
}
|