SpringBoot集成Minio
创始人
2024-11-14 13:04:42
0
public class MinIOConfig {     @Autowired     private MinIOConfigProperties minIOConfigProperties;      @Bean     public MinioClient buildMinioClient() {         return MinioClient                 .builder()                 .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())                 .endpoint(minIOConfigProperties.getEndpoint())                 .build();     } }
@Data @ConfigurationProperties(prefix = "minio") @Component public class MinIOConfigProperties implements Serializable {      private String accessKey;     private String secretKey;     private String bucket;     private String endpoint;     private String readPath;  }
public interface MinioFileService {      /**      * 下载文件      * @param pathUrl      * @param response      */     void downLoadFile(String pathUrl, HttpServletResponse response) ;      /**      * 上传文件到指定tong桶下面的指定目录      * @param bucketName   桶名称      * @param folderPath   目录名称      * @param file         文件      */     String downLoadFileByPath(String bucketName,String folderPath, MultipartFile file) throws Exception;       /**      * 上传文件      * @param file      * @return      * @throws Exception      */      String uploadFile(File file) throws Exception;       /**      * 创建临时目录      * @return      */     File createTempDir();       /**      * 删除文件      * @param pathUrl      */      void delete(String pathUrl) ;      /**      * 列出所有bucket名称      * @return      * @throws Exception      */      List listBucketNames() throws Exception;      /**      * 创建bucket      * @param bucketName      * @return      * @throws Exception      */      boolean makeBucket(String bucketName) throws Exception;      /**      * 删除bucket      * @param bucketName      * @return      * @throws Exception      */      boolean removeBucket(String bucketName) throws Exception;      /**      * 列出bucket的所有对象名称      * @param bucketName      * @return      * @throws Exception      */      List listObjectNames(String bucketName) throws Exception;        Iterable> listObjects(String bucketName) throws Exception; } 
@Slf4j @Import(MinIOConfig.class) @Service public class MinioFileServiceImpl  implements MinioFileService {       @Autowired     private MinioClient minioClient;      @Autowired     private MinIOConfigProperties minIOConfigProperties;      private final static String separator = "/";      @Value("${Temporary_file_address}")     private String Temporary_file_address;      /**      * 下载文件      *      * @param pathUrl 文件全路径      * @return 文件流      */     @Override     public  void downLoadFile(String pathUrl, HttpServletResponse response) {         String[] pathItems = pathUrl.split("/");         String originFileName = pathItems[pathItems.length - 1];         String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");         int index = key.indexOf(separator);         //String bucket = key.substring(0,index);         String filePath = key.substring(index + 1);         InputStream inputStream = null;         try {             inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());             response.setHeader("Content-Disposition", "attachment;filename=" + originFileName);             response.setContentType("application/force-download");             response.setCharacterEncoding("UTF-8");             IOUtils.copy(inputStream, response.getOutputStream());             System.out.println("下载成功");         } catch (Exception e) {             log.error("minio down file error.  pathUrl:{}", pathUrl);             e.printStackTrace();         } finally {             try {                 inputStream.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     }      @Override     public String downLoadFileByPath(String bucketName, String folderPath, MultipartFile file)  throws Exception{         String endpoint = minIOConfigProperties.getEndpoint();         // 上传文件到指定文件夹         String objectName = folderPath+"/" + file.getOriginalFilename();         PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)                 .bucket(bucketName)                 .contentType(file.getContentType())                 .stream(file.getInputStream(), file.getSize(), -1).build();         minioClient.putObject(objectArgs);         return endpoint + "/" + bucketName + "/" + objectName;      }      //    @Override //    public String uploadFile(MultipartFile file) throws Exception { //        String bucketName = minIOConfigProperties.getBucket(); //        String endpoint = minIOConfigProperties.getEndpoint(); //        InputStream inputStream = file.getInputStream(); //        // 检查存储桶是否已经存在 //        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); //        if (isExist) { //            System.out.println("Bucket already exists."); //        } else { //            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); //        } //        String originalFilename = file.getOriginalFilename(); //        //拼接生成新的UUID形式的文件名 //        String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + //                UUID.randomUUID().toString().replaceAll("-", "") //                + originalFilename.substring(originalFilename.lastIndexOf(".")); // //        PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName) //                .bucket(bucketName) //                .contentType(file.getContentType()) //                .stream(inputStream, file.getSize(), -1).build(); //        minioClient.putObject(objectArgs); //        inputStream.close(); //        //组装桶中文件的访问url //        String resUrl = endpoint + "/" + bucketName + "/" + objectName; //        return resUrl; //    }     @Override     public String uploadFile(File file) throws Exception {         String bucketName = minIOConfigProperties.getBucket();         String endpoint = minIOConfigProperties.getEndpoint();          try {             // 检查存储桶是否已经存在             if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {                 minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());             }             // 拼接生成新的UUID形式的文件名             String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) +                     UUID.randomUUID().toString().replaceAll("-", "") +                     file.getName().substring(file.getName().lastIndexOf("."));             // 上传             minioClient.uploadObject(UploadObjectArgs.builder()                     .bucket(bucketName)                     .object(objectName)                     .filename(file.getAbsolutePath())                     .build());             // 组装桶中文件的访问url             return endpoint + "/" + bucketName + "/" + objectName;         } catch (Exception e) {             log.error("上传文件 {} 失败: {}", file.getName(), e.getMessage());             e.printStackTrace();             throw new ServiceException(1000000500, "上传文件失败:" + e);         } finally {             // 删除临时文件             this.deleteTempFile(file);         }     }      /**      * 在应用启动时      * 创建临时目录      */     @Override     public File createTempDir() {         String property = System.getProperty("user.home");         // 生成或指定文件存储的目录         File dir = new File(property);         if (!dir.exists()) {             dir.mkdirs();         }         return dir;     }     /**      * 删除临时文件      * @param file file      */     private void deleteTempFile(File file) {         try {             Files.deleteIfExists(Paths.get(file.getAbsolutePath()));         } catch (IOException e) {             log.error("删除临时文件失败: {}", file.getAbsolutePath(), e);         }     }       /**      * 删除文件      *      * @param pathUrl 文件全路径      */     @Override     public void delete(String pathUrl) {         String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");         int index = key.indexOf(separator);         String bucket = key.substring(0, index);         String filePath = key.substring(index + 1);         // 删除Objects         RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();         try {             minioClient.removeObject(removeObjectArgs);         } catch (Exception e) {             log.error("minio remove file error.  pathUrl:{}", pathUrl);             e.printStackTrace();         }     }      public List listBuckets()             throws Exception {         return minioClient.listBuckets();     }      public boolean bucketExists(String bucketName) throws Exception {         boolean flag = minioClient.bucketExists( BucketExistsArgs.builder().bucket(bucketName).build());         if (flag) {             return true;         }         return false;     }      @Override     public List listBucketNames() throws Exception{         List bucketList = listBuckets();         List bucketListName = new ArrayList<>();         for (Bucket bucket : bucketList) {             bucketListName.add(bucket.name());         }         return bucketListName;     }      @Override     public boolean makeBucket(String bucketName) throws Exception{         boolean flag = this.bucketExists(bucketName);         if (!flag) {             minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());             return true;         } else {             return false;         }     }      @Override     public boolean removeBucket(String bucketName) throws Exception{         boolean flag = bucketExists(bucketName);         if (flag) {             Iterable> myObjects = listObjects(bucketName);             for (Result result : myObjects) {                 Item item = result.get();                 // 有对象文件,则删除失败                 if (item.size() > 0) {                     return false;                 }             }             // 删除存储桶,注意,只有存储桶为空时才能删除成功。             minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());             flag = bucketExists(bucketName);             if (!flag) {                 return true;             }         }         return false;     }     @Override     public List listObjectNames(String bucketName) throws Exception{         List listObjectNames = new ArrayList<>();         boolean flag = bucketExists(bucketName);         if (flag) {             Iterable> myObjects = listObjects(bucketName);             for (Result result : myObjects) {                 Item item = result.get();                 listObjectNames.add(item.objectName());             }         }         return listObjectNames;     }      public Iterable> listObjects(String bucketName) throws Exception {         boolean flag = bucketExists(bucketName);         if (flag) {             return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());         }         return null;     }  } 
public class MultipartConfigElement {     @Bean     public javax.servlet.MultipartConfigElement multipartConfigElement() {         MultipartConfigFactory factory = new MultipartConfigFactory();         factory.setLocation("/home/temp");         return factory.createMultipartConfig();     }   }

添加依赖:

              io.minio             minio             7.1.0  

配置application.yam文件:

//application.yam文件 minio:   accesskey: xxxxxxxxxxxxxxxxxxxxxxx   secretKey: xxxxxxxxxxxxxxxxxxxxx   endpoint: http://xxxxxxxx:端口号   readPath: http://xxxxxxxx:端口号 

相关内容

热门资讯

微信炸金花房卡有没有购买/微信... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:8488009许多玩家在游戏中会购买房卡来享受...
终于找到“微信炸金花链接在哪里... 微信炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡...
微信炸金花房卡链接在哪弄的/怎... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:33903369许多玩家在游戏中会购买房卡来享...
正版授权“微信牛牛房卡客服微信... 九酷大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡来...
微信玩链接炸金花房卡/战皇大厅... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:55051770许多玩家在游戏中会购买房卡来享...
买房卡的链接炸金花房卡/微信斗... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:8488009许多玩家在游戏中会购买房卡来享受...
一分钟了解“牛牛房卡哪里有卖的... 起点大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡来...
微信群牛牛房卡怎么买/新九天大... 斗牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:33903369许多玩家在游戏中会购买房卡来享受...
房卡必备教程“微信牛牛房卡在哪... 新全游牛牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:15984933许多玩家在游戏中会购买房卡...
微信群链接拼三张房卡/新518... 拼三张是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:55051770许多玩家在游戏中会购买房卡来享...
一分钟推荐“炸金花房卡链接怎么... 金牛座金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡...
微信里面炸金花房卡在哪买/新蓝... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:8488009许多玩家在游戏中会购买房卡来享受...
一分钟了解“哪里有卖微信炸金花... 微信炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡...
在哪里买斗牛微信房卡/茄子娱乐... 斗牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:33903369许多玩家在游戏中会购买房卡来享受...
正版授权“牛牛房卡哪里有卖的”... 牛牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡来享受...
炸金花房卡链接在哪弄的/牛牛房... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:55051770许多玩家在游戏中会购买房卡来享...
微信炸金花房卡如何购买/悟空大... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:8488009许多玩家在游戏中会购买房卡来享受...
一分钟了解“炸金花房卡专卖店联... 新神盾是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:15984933许多玩家在游戏中会购买房卡来享...
微信炸金花房间怎么弄/新皇豪大... 炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:33903369许多玩家在游戏中会购买房卡来享...
ia实测“微信金花群怎么买房卡... 金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡来享受...