【发布时间】:2017-11-10 09:42:26
【问题描述】:
我有一个 Spring Boot Web 应用程序,它生成扩展名为 .xlsx 的 Microsoft Excel 文件。
如果我尝试从浏览器调用localhost:8080/report/stats 下载文件,它会返回正确的文件,我总是可以成功打开它。
但是,当我通过单击按钮从网页下载文件时,我得到了一个错误的文件,我无法打开它。
我在JS上有以下部分:
$.ajax({
url: 'report/stats',
type: "GET",
success: function (data) {
var link = document.createElement('a');
link.download = 'report.xlsx';
link.href = 'data:,' + data;
link.click();
}
});
控制器:
@GetMapping("stats")
public ResponseEntity downloadStatsReport() throws IOException {
return fileResponse(excelReportService.create(new StatFilter()));
}
private ResponseEntity fileResponse(File report) throws IOException {
InputStreamResource resource = new InputStreamResource(new FileInputStream(report));
return ResponseEntity.ok()
.contentLength(report.length())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + report.getName())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
为什么从浏览器下载效果很好,而从 JS 下载不行?
打开文件错误:
YES已被点击:
没有需要点击:
【问题讨论】:
-
@DharmaSaputra,感谢您的回复,我已经尝试过该解决方案并且确实有效,但是使用以下解决方案无法知道请求何时完成或没有...
标签: javascript excel spring-boot