用springboot整合minio实现多文件批量上传
时间: 2024-01-31 10:07:22 浏览: 186
springboot实现多文件上传功能
首先,需要引入minio的依赖:
```
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.2</version>
</dependency>
```
然后,在application.properties中配置minio的连接信息:
```
minio.url=http://localhost:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=test
```
接着,创建一个MinioService类,用于处理文件上传和下载:
```
@Service
public class MinioService {
@Value("${minio.url}")
private String minioUrl;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
@Value("${minio.bucketName}")
private String bucketName;
private final MinioClient minioClient = new MinioClient(minioUrl, accessKey, secretKey);
public void upload(MultipartFile file) throws Exception {
// 生成文件名
String originalFilename = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
// 上传文件
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.stream(file.getInputStream(), file.getSize(), -1)
.contentType(file.getContentType())
.build());
}
public InputStream download(String fileName) throws Exception {
// 下载文件
return minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build());
}
}
```
最后,在Controller中使用MinioService处理上传和下载请求:
```
@RestController
public class MinioController {
@Autowired
private MinioService minioService;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile[] files) {
try {
for (MultipartFile file : files) {
minioService.upload(file);
}
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
return "上传失败";
}
}
@GetMapping("/download")
public ResponseEntity<InputStreamResource> download(@RequestParam("fileName") String fileName) {
try {
InputStream inputStream = minioService.download(fileName);
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=" + fileName);
return ResponseEntity.ok().headers(headers).contentLength(inputStream.available())
.contentType(MediaType.parseMediaType("application/octet-stream")).body(inputStreamResource);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}
```
这样,就可以使用Spring Boot和Minio实现多文件批量上传了。
阅读全文