关于minio在Java中的使用

一、从minio中获取流转成base64

1、在pom文件中加入maven依赖

<!--minio-->
<dependency>
     <groupId>io.minio</groupId>
      <artifactId>minio</artifactId>
      <version>6.0.11</version>
</dependency>

2、写util

@Component
public class FlieUtil {
    @Autowired
    private MinioClient minioClient;
    /**
     * 文件转成base64
     * */
    public String getBase64String(String pdfName) throws Exception {
        if (path == null || path.isEmpty()) {
            throw new Exception("工具文件转base64中path为空!!!");
        }
        Boolean DetermineExists = this.getDetermineExists("bucketName", pdfName);
        String strBase64="";
        if (DetermineExists){
            InputStream is = null;
            ByteArrayOutputStream os = null;
            byte[] buff = new byte[1024];
            int len = 0;
            try {
                is = minioClient.getObject("qdbucket", pdfName);
                os = new ByteArrayOutputStream();
                while ((len = is.read(buff)) != -1) {
                    os.write(buff, 0, len);
                }
                os.flush();
                os.toByteArray();
                strBase64 = Base64.getEncoder().encodeToString(os.toByteArray());
            } catch (IOException e) {
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {}
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {}
                }
            }
            return strBase64;
        }
        return "minio中没有这个文件";
    }
    
    /**
    *这个是查看minio中是否存在这个文件
    *存在返回true
    *不存在则返回false
    *bucketName 桶的名字
    *objectName 文件的名字
    */
    public Boolean getDetermineExists(String bucketName,String objectName){
        try {
            minioClient.getObject(bucketName,objectName);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}    

3、在service中的用法

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
   	 @Autowired
   	 private FlieUtil flieUtil;
     public String getBase64String(String pdfName) {
         String base64=flieUtil.getBase64String(pdfName);
         return base64;
     }
   	 
}
posted @ 2022-09-02 15:00  天使中的恶魔  阅读(945)  评论(0编辑  收藏  举报