若依minio上传下载
时间: 2025-01-20 20:56:27 浏览: 50
### 若依框架中集成MinIO实现文件上传和下载
#### 集成环境配置
为了使若依框架能够支持MinIO的文件操作,需先完成依赖引入。在`pom.xml`文件内加入MinIO SDK的相关依赖[^1]。
```xml
<dependency>
<groupId>io.minio</groupId>
<artifactId|minio|version>8.5.7</version>
</dependency>
```
#### 初始化MinIO客户端
通过创建一个工具类来初始化MinIO Client,在该类中定义连接到MinIO服务器所需的信息如端点URL、访问密钥等参数[^2]。
```java
import io.minio.MinioClient;
public class MinioUtil {
private static final String ENDPOINT = "http://your-minio-server-url";
private static final String ACCESS_KEY = "your-access-key";
private static final String SECRET_KEY = "your-secret-key";
public static MinioClient getMinioClient() throws Exception{
return new MinioClient(ENDPOINT,ACCESS_KEY,SECRET_KEY);
}
}
```
#### 文件上传接口设计
基于Spring Boot控制器模式编写用于处理HTTP请求的方法,接收从前端发送过来的数据流并调用MinIO API执行实际的文件保存工作。
```java
@RestController
@RequestMapping("/minio")
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file){
try{
MinioClient minioClient = MinioUtil.getMinioClient();
InputStream inputStream = file.getInputStream();
ObjectWriteResponse response = minioClient.putObject(
PutObjectArgs.builder()
.bucket("test-bucket-name")
.object(file.getOriginalFilename())
.stream(inputStream,file.getSize(),-1)
.contentType(file.getContentType())
.build());
return ResponseEntity.ok("Success");
}catch(Exception e){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
```
#### 文件下载接口开发
同样利用RESTful风格的服务提供对外暴露的API路径,允许用户指定要获取的对象名称从而触发相应的检索逻辑。
```java
@GetMapping("/download/{fileName}")
public void downloadFile(HttpServletResponse response,@PathVariable String fileName)throws IOException{
try{
MinioClient minioClient = MinioUtil.getMinioClient();
GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket("test-bucket-name").object(fileName).build();
try(InputStream stream = minioClient.getObject(getObjectArgs)){
IOUtils.copy(stream,response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
```
阅读全文
相关推荐


















