springboot 输出txt下载,
时间: 2023-12-21 21:25:24 浏览: 71
要实现Spring Boot输出txt文件下载,可以使用以下步骤:
1.在pom.xml文件中添加依赖项
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2.创建一个RESTful API来提供txt文件下载
```java
@RestController
public class DownloadController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
String fileName = "example.txt";
ByteArrayResource resource = new ByteArrayResource("Hello, world!".getBytes());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
.contentType(MediaType.TEXT_PLAIN)
.contentLength(resource.contentLength())
.body(resource);
}
}
```
3.访问http://localhost:8080/download将下载txt文件。
阅读全文