背景(需求)
在浏览器上点击按钮下载txt文件时,会直接在浏览器打开文件的。那如何使用弹窗下载呢?
前提
- 需要下载的文件,已经在服务器上面,文件结构为 **/download/report/**.txt
- 文件保存的文件夹比较有规律
- 前端的下载按钮,绑定的是文件的URL
分析
下载文件,其实是下载服务器上面的文件,看URL也能看出,那既然是URL,那就可以重写URL了。
实现
主要是需要修改httpheader
response.addHeader("Content-Disposition","attachment;filename="文件名称.txt");
设置下载URL
@RestController
public class CommonController {
@GetMapping("/download/{path}/{name:.+}")
public ResponseEntity<FileSystemResource> downloadFile(@PathVariable("path") String path, @PathVariable("name") String fileName) {
File file = new File(System.getProperty("user.dir") +
File.separator + "dow