前台请求的是文件数组,需要下载多个文件 ,java spring boot 从s3下载zip返给前台浏览器,直接浏览器下载
时间: 2024-11-26 22:22:06 浏览: 22
在Spring Boot项目中,如果你需要从Amazon S3下载多个文件并返回给前台浏览器直接下载,你可以这样做:
1. **添加依赖**:
首先,在`pom.xml`中引入AWS SDK for Java (S3客户端) 和 Spring Web相关的依赖:
```xml
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. **配置AWS客户端**:
在`application.properties`或`application.yml`中添加AWS的凭证信息:
```
aws.accessKeyId=your_access_key
aws.secretKey=your_secret_key
s3.bucketName=your_s3_bucket_name
```
3. **创建服务类**:
创建一个`S3Service`类,用于获取S3文件并触发下载:
```java
@Service
public class S3ServiceImpl implements S3Service {
private AmazonS3 s3Client;
@Autowired
public void setS3Client(AmazonS3 amazonS3) {
this.s3Client = amazonS3;
}
@Override
public ResponseEntity<byte[]> downloadZip(String[] fileKeys) throws IOException {
List<S3Object> objects = s3Client.listObjects(BucketRequestBuilder.bucketName(bucketName()).build())
.getObjectSummaries()
.stream()
.filter(obj -> Arrays.asList(fileKeys).contains(obj.getKey()))
.collect(Collectors.toList());
if (objects.isEmpty()) {
throw new FileNotFoundException("No files found with the given keys.");
}
S3Object object = objects.get(0); // Assuming single file per request
byte[] data = getObjectContent(object);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(data, headers, HttpStatus.OK);
}
private byte[] getObjectContent(S3Object obj) {
try {
return obj.getObjectContent().array();
} catch (IOException e) {
throw new RuntimeException("Error downloading file from S3.", e);
}
}
}
```
4. **暴露API**:
在Controller中,通过`@GetMapping`处理GET请求,接收文件键数组,并调用`downloadZip`方法:
```java
@RestController
public class FileDownloadController {
private final S3Service s3Service;
@Autowired
public FileDownloadController(S3Service s3Service) {
this.s3Service = s3Service;
}
@GetMapping("/download-zip")
public ResponseEntity<byte[]> downloadFiles(@RequestParam String[] fileKeys) {
try {
return s3Service.downloadZip(fileKeys);
} catch (Exception e) {
log.error("Error while downloading zip.", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.TEXT_PLAIN)
.body(e.getMessage());
}
}
}
```
5. **浏览器端处理**:
后端返回的响应会被自动设置为`Content-Disposition: attachment`头,浏览器会感知到这是下载内容而不是浏览,所以可以直接下载。
阅读全文