SpringBoot集成Minio

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<String> 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<String> listObjectNames(String bucketName) throws Exception;


     Iterable<Result<Item>> 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<Bucket> 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<String> listBucketNames() throws Exception{
        List<Bucket> bucketList = listBuckets();
        List<String> 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<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> 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<String> listObjectNames(String bucketName) throws Exception{
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }

    public Iterable<Result<Item>> 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();
    }


}

添加依赖:

 <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>7.1.0</version>
 </dependency>

配置application.yam文件:

//application.yam文件
minio:
  accesskey: xxxxxxxxxxxxxxxxxxxxxxx
  secretKey: xxxxxxxxxxxxxxxxxxxxx
  endpoint: http://xxxxxxxx:端口号
  readPath: http://xxxxxxxx:端口号
Spring Boot项目中集成Minio,你可以按照以下步骤进行操作: 1. 首先,你需要在项目的pom.xml文件中添加Minio的依赖项。你可以使用以下代码片段来添加依赖项: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.5.1</version> </dependency> ``` 2. 接下来,你需要在你的应用程序中使用Minio的API进行连接和操作。你可以参考以下代码片段来完成这一步骤: ```java import io.minio.MinioClient; // 创建MinioClient对象 MinioClient minioClient = new MinioClient("http://localhost:9000", "access-key", "secret-key"); // 检查存储桶是否存在 boolean isExist = minioClient.bucketExists("bucket-name"); if (isExist) { System.out.println("存储桶已存在!"); } else { // 创建存储桶 minioClient.makeBucket("bucket-name"); System.out.println("存储桶创建成功!"); } ``` 3. 最后,你需要在你的应用程序的配置文件(例如application.yml或application.properties)中配置Minio的连接信息。你可以参考以下代码片段来完成这一步骤: ```yaml minio: url: 129.0.0.1:9000 # 替换成你自己的Minio服务端地址 access-key: minioadmin secret-key: minioadmin bucket-name: ding_server ``` 这样,你就成功地集成Minio到你的Spring Boot项目中,并可以使用Minio的API进行对象存储操作了。记得替换相应的连接信息和存储桶名称以适应你的项目需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Springboot集成Minio](https://blog.csdn.net/qq_45374325/article/details/129464067)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot整合minio](https://blog.csdn.net/qq_36090537/article/details/128100423)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值