背景:我需要一个简单的文件下载功能,例如:输入 /Users/Documents//filedownload/src/main/resources/a.txt会下载文件到本地
准备:新建一个简单的 springboot 服务,直接上代码,如有需要 pom.xml 放在最后
controller
@RestController
@Slf4j
public class FileDownloadController {
@PostMapping("/download")
public ResponseEntity<?> downloadFile(@RequestParam("fileName") String fileName) {
try {
// 拼接完整的文件路径
String fullPath = fileName;
log.info("接收到文件路径为:{}",fileName);
// 检查文件是否存在
if (!Files.exists(Paths.get(fullPath))) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File not found.");
}
// 使用FileSystemResource加载文件
FileSystemResource file = new FileSystemResource(fullPath);
// 设置HTTP头,指示客户端这是一个文件下载
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFilename());
// 返回文件资源和相应的HTTP头
return ResponseEntity.ok()
.headers(headers)
.body(file);
} catch (Exception e) {
// 处理其他未知异常
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred while processing the request.");
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>filedownload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>filedownload</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2023.0.2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>