spring boot 下载文件
时间: 2024-12-27 15:11:01 浏览: 51
在Spring Boot中下载文件通常涉及到HTTP响应头设置和文件内容提供。你可以通过`ResponseEntity`或` ResponseEntity流`来完成这个操作。以下是基本步骤:
1. **创建资源文件**:首先确保你的文件存储在一个合适的目录下,比如`src/main/resources/static`。
2. **获取文件路径**:使用`Resource`类,传入文件的URL路径。
```java
Resource resource = new ClassPathResource("file-to-download.txt");
```
3. **设置HTTP响应头**:使用`ResponseEntity`构建一个HTTP响应,设置正确的Content-Disposition和Content-Type。
```java
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("filename", "downloaded-file-name.txt");
// 或者直接使用 ResponseEntity
ResponseEntity<InputStreamResource> responseEntity = ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(resource.getInputStream()));
```
4. **返回响应**:最后,调用`WebClient`、`RestTemplate`或其他REST客户端发送该响应。
```java
return webClient.get().uri("/download").exchange()
.expectStatusCodes(HttpStatus.OK)
.retrieve()
.toEntity(InputStreamResource.class);
```
阅读全文
相关推荐












