集成步骤
<minio.version>7.1.0</minio.version>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>${minio.version}</version>
</dependency>
spring:
servlet:
multipart:
enabled: true
max-file-size: 10MB
minio:
url: http://11.11.11.224:9000
bucketName: demo
accessKey: minioadmin
secretKey: minioadmin
@Component
public class Minio {
private final Logger logger = LoggerFactory.getLogger(Minio.class);
@Value("${minio.url}")
private String url;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
private String thumborWidth;
public CommonResult minioUpload(MultipartFile file, String fileName, String bucketName) {
try {
MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
boolean bucketExists = minioClient.bucketExists(bucketName);
if (bucketExists) {
logger.info("仓库" + bucketName + "已经存在,可直接上传文件。");
} else {
minioClient.makeBucket(bucketName);
}
if (file.getSize() <= 20971520) {
if (fileName == null) {
fileName = file.getOriginalFilename();
fileName = fileName.replaceAll(" ", "_");
}
minioClient.putObject(bucketName, fileName, file.getInputStream(), new PutObjectOptions(file.getInputStream().available(), -1));
logger.info("成功上传文件 " + fileName + " 至 " + bucketName);
String fileUrl = bucketName + "/" + fileName;
Map<String, Object> map = new HashMap<String, Object>();
map.put("fileUrl", fileUrl);
map.put("bucketName", bucketName);
map.put("originFileName", fileName);
return CommonResult.success(map);
} else {
throw new Exception("请上传小于20mb的文件");
}
} catch (Exception e) {
e.printStackTrace();
if (e.getMessage().contains("ORA")) {
return CommonResult.failed("上传失败:【查询参数错误】");
}
return CommonResult.failed("上传失败:【" + e.getMessage() + "】");
}
}
public boolean isFileExisted(String fileName, String bucketName) {
InputStream inputStream = null;
try {
MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
inputStream = minioClient.getObject(bucketName, fileName);
if (inputStream != null) {
return true;
}
} catch (Exception e) {
logger.error(e.getMessage());
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public boolean delete(String bucketName,String fileName) {
try {
MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
minioClient.removeObject(bucketName,fileName);
return true;
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
}
public CommonResult downloadFile(String objectName,String bucketName, HttpServletResponse response) {
try {
MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
InputStream file = minioClient.getObject(bucketName,objectName);
String filename = new String(objectName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
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 CommonResult.success(objectName + "下载成功");
} catch (Exception e) {
e.printStackTrace();
if (e.getMessage().contains("ORA")) {
return CommonResult.success("下载失败:【查询参数错误】");
}
return CommonResult.success("下载失败:【" + e.getMessage() + "】");
}
}
public InputStream getFileInputStream(String objectName,String bucketName) {
try {
MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
return minioClient.getObject(bucketName,objectName);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return null;
}
}
@Api(tags = "MinioController", description = "MinIO存储管理Controller")
@RequestMapping("/minio")
@RestController
public class MinioController {
private static final Logger logger = LoggerFactory.getLogger(MinioController.class);
@Value("${minio.bucketName}")
private String bucketName;
@Autowired
private Minio minio;
@ApiOperation("下载文件Minio")
@RequestMapping("/download/**")
@SneakyThrows
public void download(HttpServletRequest request, HttpServletResponse response) {
String imgPath = extractPathFromPattern(request);
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String bucketName = "";
String fileName = "";
response.setContentType("application/octet-stream");
if (StringUtils.isNotEmpty(imgPath)) {
String[] split = imgPath.split("/");
bucketName = split[0];
fileName = split[1];
}
inputStream = minio.getFileInputStream(fileName, bucketName);
String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
servletOutputStream = response.getOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) > 0) {
servletOutputStream.write(buffer, 0, len);
}
servletOutputStream.flush();
inputStream.close();
servletOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("上传文件失败:{}", e.getMessage());
}finally {
if (null != inputStream){
try {
inputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if (null != servletOutputStream){
try {
servletOutputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
@ApiOperation("删除文件")
@RequestMapping("/delete/**")
@SneakyThrows(Exception.class)
public CommonResult delete(HttpServletRequest request, HttpServletResponse response) {
String imgPath = extractPathFromPattern(request);
try {
String bucketName = "";
String fileName = "";
if (StringUtils.isNotEmpty(imgPath)) {
String[] split = imgPath.split("/");
bucketName = split[0];
fileName = split[1];
}
minio.delete(bucketName, fileName);
return CommonResult.success("删除成功");
}catch (Exception e) {
e.printStackTrace();
logger.error("删除失败:{}", e.getMessage());
}
return CommonResult.failed("删除失败");
}
@PostMapping(value = "/upload")
@ApiOperation(value = "图片上传")
public CommonResult upload(HttpServletRequest request, HttpServletResponse response) {
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mf = multipartRequest.getFile("file");
String orgName = "";
String fileName = "";
if (mf != null){
orgName = mf.getOriginalFilename();
fileName = System.currentTimeMillis()+"_"+ orgName.replaceAll(" ", "_");
}
boolean exist = minio.isFileExisted(fileName, bucketName);
if (exist) {
logger.error("文件 " + fileName + " 已经存在");
return CommonResult.failed("文件已存在");
}
CommonResult result = minio.minioUpload(mf,fileName,bucketName);
return result;
} catch (Exception e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
}
return CommonResult.failed("上传失败");
}
@GetMapping(value = "/view/**")
public void minioView(HttpServletRequest request, HttpServletResponse response) {
String imgPath = extractPathFromPattern(request);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String bucketName = "";
String fileName = "";
response.setContentType("image/jpeg;charset=utf-8");
if (StringUtils.isNotEmpty(imgPath)){
String[] split = imgPath.split("/");
bucketName = split[0];
fileName = split[1];
}
inputStream =minio.getFileInputStream(fileName,bucketName);
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
} catch (IOException e) {
logger.error("预览图片失败" + e.getMessage());
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
private static String extractPathFromPattern(final HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}
}