springboot 下载文件接口
时间: 2023-08-10 10:21:25 浏览: 123
在Spring Boot中提供了下载文件的接口,可以通过以下步骤实现:
1.在Controller中编写下载文件的接口
```java
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
// 设置文件名和文件路径
String fileName = "example.txt";
String filePath = "/path/to/file/example.txt";
// 获取要下载的文件
File file = new File(filePath);
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentLength((int) file.length());
// 读取文件并输出到响应流
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
```
2.在前端页面中添加下载按钮并调用该接口
```html
<a href="/download" download="example.txt">Download</a>
```
其中download属性可以设置下载文件的名称。
这样就可以实现在Spring Boot中下载文件的功能了。
阅读全文
相关推荐


















