springboot集成minio实现文件批量下载
时间: 2024-05-15 11:08:56 浏览: 289
SpringBoot(31) 整合MinIO实现文件上传与下载
在Spring Boot中集成Minio实现文件批量下载的方法如下:
1. 首先,确保已经在Spring Boot项目中引入了Minio的依赖。可以在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.6</version>
</dependency>
```
2. 在Spring Boot的配置文件中配置Minio的连接信息。可以在`application.properties`或`application.yml`文件中添加以下配置:
```yaml
minio:
url: http://localhost:9000
access-key: your-access-key
secret-key: your-secret-key
bucket-name: your-bucket-name
```
请将`your-access-key`、`your-secret-key`和`your-bucket-name`替换为实际的Minio连接信息。
3. 创建一个文件下载的Controller,用于处理文件下载的请求。可以创建一个`FileController`类,并添加以下代码:
```java
import io.minio.MinioClient;
import io.minio.GetObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
@Controller
public class FileController {
@Autowired
private MinioClient minioClient;
@GetMapping("/download/{filename}")
public ResponseEntity<InputStreamResource> downloadFile(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
try {
InputStream inputStream = minioClient.getObject(
GetObjectArgs.builder()
.bucket("your-bucket-name")
.object(filename)
.build()
);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));
return ResponseEntity.ok()
.headers(headers)
.body(new InputStreamResource(inputStream));
} catch (MinioException e) {
// 处理Minio异常
e.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null; }
}
}
```
请将`your-bucket-name`替换为实际的Minio存储桶名称。
4. 启动Spring Boot应用程序,并访问`/download/{filename}`接口来下载文件。将`{filename}`替换为实际要下载的文件名。
阅读全文