package com.meritdata.cloud.multianalysis.utils;
import com.meritdata.cloud.multianalysis.properties.MultianalyProperties;
import com.meritdata.cloud.resultmodel.ResultBody;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
/**
* @Author sunyt
* @Date 2022/6/6 10:02
* @Description Minio 相关处理工具类
*/
@Slf4j
@Component
public class MinioUtil {
@Autowired
private MultianalyProperties multianalyProperties;
public MinioClient getMinioClient() {
try {
return new MinioClient(multianalyProperties.getMinioEndpoint(), multianalyProperties.getMinioAccessKey(), multianalyProperties.getMinioSecretKey());
} catch (Exception e) {
e.printStackTrace();
log.error("Minio connect error", e);
return null;
}
}
/**
* 下载文件
*
* @param id 当前文件对应id
* @param response
* @param fileName 要返回的excel文件名称
*/
public void downLoad(String id, HttpServletResponse response, String fileName) {
try {
MinioClient minioClient = getMinioClient();
InputStream fileInputStream = minioClient.getObject(multianalyProperties.getMinioBucketName(), id);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
IOUtils.copy(fileInputStream, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上传文件
*
* @param file
* @param id 当前文件对应id
* @return
*/
public ResultBody uploadFile(MultipartFile file, String id) {
InputStream fileInput = null;
try {
MinioClient minioClient = getMinioClient();
//存入bucket不存在则创建
if (!minioClient.bucketExists(multianalyProperties.getMinioBucketName())) {
minioClient.makeBucket(multianalyProperties.getMinioBucketName());
}
String filename = file.getOriginalFilename();
// 存储文件
fileInput = file.getInputStream();
minioClient.putObject(multianalyProperties.getMinioBucketName(), id, fileInput, file.getContentType());
return ResultBody.success(filename);
} catch (Exception e) {
log.error("File upload error!", e);
return ResultBody.failure("文件上传失败!");
} finally {
try {
if(fileInput != null) {
fileInput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根据文件对应id 删除文件
*
* @param id
* @return
* @throws ParseException
*/
public void delMinioFile(String id) {
try {
MinioClient minioClient = getMinioClient();
minioClient.removeObject(multianalyProperties.getMinioBucketName(), id);
} catch (Exception e) {
log.error("Minio delete error", e);
throw new RuntimeException("删除文件失败");
}
}
}
引入的pom
io.minio
minio
3.0.10