springboot 实现文件的下载
时间: 2024-05-03 10:23:09 浏览: 8
可以通过以下步骤实现Spring Boot的文件下载功能:
1. 在Controller中添加一个@RequestMapping注解的方法来处理文件下载请求。
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
// TODO:实现文件下载逻辑
}
```
2. 在downloadFile方法中,使用Resource接口来封装要下载的文件,并将其返回给客户端。在这里我们使用FileSystemResource实现Resource接口。
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
String fileName = "example.txt";
Resource resource = new FileSystemResource("path/to/" + fileName);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(resource);
}
```
3. 在返回的ResponseEntity中设置Content-Disposition头来告诉浏览器该文件应该作为附件下载,而不是在浏览器中打开。
4. 如果要支持多种文件类型的下载,可以根据文件类型确定Content-Type头。例如,对于PDF文件,Content-Type应该是"application/pdf"。
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
String fileName = "example.pdf";
Resource resource = new FileSystemResource("path/to/" + fileName);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
}
```
5. 最后,需要确保文件存在,否则应该返回404错误。
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws FileNotFoundException {
String fileName = "example.pdf";
File file = new File("path/to/" + fileName);
if (!file.exists()) {
throw new FileNotFoundException("文件不存在!");
}
Resource resource = new FileSystemResource(file);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
}
```
以上就是Spring Boot实现文件下载的基本步骤,根据实际需要可以进行进一步的优化。