Minio集成

文章目录


集成步骤

  • 依赖导入
	<minio.version>7.1.0</minio.version>
	<!--MinIO JAVA SDK-->
    <dependency>
           <groupId>io.minio</groupId>
           <artifactId>minio</artifactId>
           <version>${minio.version}</version>
       </dependency>
  • yml配置
spring:
  servlet:
    multipart:
      #开启文件上传
      enabled: true
      # 限制文件上传大小为10MB
      max-file-size: 10MB
#自定义配置
minio:
  url: http://11.11.11.224:9000 #MinIO服务所在地址
  bucketName: demo  #存储桶名称
  accessKey: minioadmin #访问的key/用户名
  secretKey: minioadmin #访问的秘钥/密码
  • 配置类Minio Bean
@Component
public class Minio {

    private final Logger logger = LoggerFactory.getLogger(Minio.class);
    
    //minio地址+端口
    @Value("${minio.url}")
    private String url;
    //minio用户名
    @Value("${minio.accessKey}")
    private String accessKey;
    //minio密码
    @Value("${minio.secretKey}")
    private String secretKey;
//    //文件桶名称
//    @Value("${minio.bucketName}")
//    private String bucketName;

//    //失效日期
//    private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;



    /**
     * 缩略图大小
     */
//    @Value("${minio.thumbor.width}")
    private String thumborWidth;


    /**
     * Minio文件上传
     * @param file 文件实体
     * @param fileName 修饰过的文件名 非源文件名
     * @param bucketName 所存文件夹(桶名)
     * @return
     */
    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) {
                // fileName为空,说明要使用源文件名上传
                if (fileName == null) {
                    fileName = file.getOriginalFilename();
                    fileName = fileName.replaceAll(" ", "_");
                }
                // minio仓库名
                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() + "】");
        }
    }



    /**
     * 判断文件是否存在
     * @param fileName 文件名
     * @param bucketName 桶名(文件夹)
     * @return
     */
    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;
    }


    /**
     * 删除文件
     * @param bucketName 桶名(文件夹)
     * @param fileName 文件名
     * @return
     */
    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;
        }
    }

    /**
     * 下载文件
     * @param objectName 文件名
     * @param bucketName 桶名(文件夹)
     * @param response
     * @return
     */
    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() + "】");
        }
    }
    
    /**
     * 获取文件流
     * @param objectName 文件名
     * @param bucketName 桶名(文件夹)
     * @return
     */
    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;
    }
}
  • controller层
@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) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        // 其余处理略
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String bucketName = "";
            String fileName = "";
//            response.setContentType("image/jpeg;charset=utf-8");
            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) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        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("删除失败");
    }


    /**
     *
     * @param request
     * @param response
     * @return
     */
    @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(" ", "_");
            }
            // 步骤一、判断文件是否存在过 存在则不能上传(Minio服务器上传同样位置的同样文件名的文件时,新的文件会把旧的文件覆盖掉)
            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("上传失败");
    }

    /**
     * 预览图片
     * 请求地址:http://localhost:8080/common/minio/view/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/view/**")
    public void minioView(HttpServletRequest request, HttpServletResponse response) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        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);
                }
            }
        }

    }



    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
     * @param request
     * @return
     */
    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);
    }




}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值