SpringBoot整合Minio

SpringBoot整合Minio

1、添加依赖

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

2、MinioConfig

在这里插入图片描述

@Configuration
public class MinioConfig {
  	// 这是从minio生成的密钥
    private static final String ACCESS_KEY = "pkRecBbz3DqdkLy6Ol6Z";
    private static final String SECRET_KEY = "ZK3OelmZYjlxxxxxlWKxn4MwxxxxxxxxxH3EY";
  
  	// 注意这里是9000端口,如果自已映射了其他的要换成对应的
    private static final String URL = "http://xxxx:9000";

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder().endpoint(URL).credentials(ACCESS_KEY, SECRET_KEY).build();
    }
}

3、MinioUtil

这里的bucket是在minio里面创建的桶

@Component
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;

    public void upload(InputStream inputStream, String filename, long size, String contentType) {
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket("public")
                    .object(filename)
                    .stream(inputStream, size, -1)
                    .contentType(contentType)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public InputStream download(String filename) {
        try {
            return minioClient.getObject(GetObjectArgs.builder()
                    .bucket("public")
                    .object(filename)
                    .build()
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void delete(String filename) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket("public")
                    .object(filename)
                    .build()
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String preview(String filename) {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket("public")
                    .object(filename)
                    .expiry(7, TimeUnit.DAYS)
                    .build()
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

4、OSSService

@Service
public class OSSService {

    @Autowired
    private MinioUtil minioUtil;

    public void upload(MultipartFile file) {
        try {
            minioUtil.upload(file.getInputStream(), file.getOriginalFilename(), file.getSize(), file.getContentType());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public InputStream download(String filename) {
        return minioUtil.download(filename);
    }

    public void delete(String filename) {
        minioUtil.delete(filename);
    }

    public String preview(String filename) {
        return minioUtil.preview(filename);
    }
}

5、OSSController

@RestController
@RequestMapping("/api/oss")
public class OSSController {

    @Autowired
    private OSSService ossService;

    @RequestMapping("/hello")
    public ResponseEntity<?> hello() {
        return ResponseEntity.Success("hello world!");
    }

    @PostMapping("/upload")
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {
        ossService.upload(file);
        return ResponseEntity.Success("upload file success");
    }

    @RequestMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
        InputStream inputStream = ossService.download(filename);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setContentType("application/octet-stream");
        IOUtils.copy(inputStream, response.getOutputStream());
    }

    @RequestMapping("/delete/{filename}")
    public ResponseEntity<?> delete(@PathVariable String filename) {
        ossService.delete(filename);
        return ResponseEntity.Success("delete file success");
    }

    @RequestMapping("/preview/{filename}")
    public ResponseEntity<?> preview(@PathVariable String filename) {
        String url = ossService.preview(filename);
        return ResponseEntity.Success(url);
    }
}
整合MinioSpring Boot可以通过以下几个步骤完成: 1. 首先,需要在pom.xml文件中添加Minio的依赖项。你可以使用以下代码片段添加依赖项: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.4.3</version> </dependency> ``` 2. 接下来,在application.yml(或application.properties)文件中配置Minio的连接信息。你需要提供Minio服务端的地址、访问密钥和存储桶名称。以下是一个示例: ```yaml minio: url: 129.0.0.1:9000 access-key: minioadmin secret-key: minioadmin bucket-name: ding_server ``` 3. 最后,在你的代码中使用Minio客户端库进行操作。你可以根据需要使用Minio的API来上传、下载和管理对象。以下是一个使用Minio客户端库的示例: ```java import io.minio.MinioClient; import io.minio.errors.MinioException; // 创建Minio客户端 MinioClient minioClient = new MinioClient("http://localhost:9000", "minioadmin", "minioadmin"); // 上传对象到Minio存储桶 minioClient.putObject("your-bucket-name", "your-object-name", "/path/to/your-file"); // 下载对象从Minio存储桶 minioClient.getObject("your-bucket-name", "your-object-name", "/path/to/save/downloaded-file"); // 列出Minio存储桶中的所有对象 Iterable<Result<Item>> results = minioClient.listObjects("your-bucket-name"); for (Result<Item> result : results) { Item item = result.get(); System.out.println(item.objectName()); } // 删除Minio存储桶中的对象 minioClient.removeObject("your-bucket-name", "your-object-name"); ``` 以上就是在Spring Boot整合Minio的基本步骤。你可以根据具体需求进行进一步的操作和配置。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [springboot整合minio](https://blog.youkuaiyun.com/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%"] - *3* [SpringBoot整合Minio](https://blog.youkuaiyun.com/weixin_46573014/article/details/128476327)[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
发出的红包

打赏作者

眼眸流转

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值