springboot文件打包下载
时间: 2024-01-13 10:02:14 浏览: 38
以下是使用Spring Boot实现文件下载的简单示例:
1. 首先,需要在pom.xml文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. 创建一个控制器类,其中一个方法处理文件下载请求:
```java
@RestController
public class FileDownloadController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {
File file = new File("path/to/file");
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}
```
3. 在上面的方法中,我们首先创建一个文件对象,然后使用文件输入流来创建一个输入流资源。接下来,我们创建一个HttpHeaders对象并将文件名添加到Content-Disposition标头中。最后,我们使用ResponseEntity构建器方法来构建响应实体。
4. 在应用程序的配置文件中,我们需要配置文件的路径:
```properties
file.path = /path/to/file
```
5. 最后,我们可以使用以下URL来下载文件:
```
http://localhost:8080/download
```
在浏览器中访问此URL时,将下载指定的文件。