javascript - 使用java脚本和spring boot下载文件
问题描述
这是我的 javascript 代码:
$('#downloadTraining').on('click', function () {
$.get(restbase() + "/download-training/" + $('[name=trainingId]').val()).done(function(data) {
}).fail(function(data) {
errorAlert();
}).always(function(data) {
});
});
这是我的 Spring Boot 控制器方法:
@GetMapping("/r/download-training/{trainingId}")
public ResponseEntity<InputStreamResource> download(@PathVariable("trainingId") Integer trainingId) throws FileNotFoundException, JRException, IOException{
File file = jasperReportService.createTrainingReport(trainingId);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
// Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
// Content-Type
.contentType(MediaType.parseMediaType("application/octet-stream"))
// Contet-Length
.contentLength(file.length()) //
.body(resource);
}
从 javascript 调用 get 方法是有效的。正在获取文件。但它不下载文件。有什么我需要添加到 javascript 或 Java 中的错误吗?
响应和请求标头: http: //prntscr.com/lh01zx
解决方案
我有一个解决方案,但我不知道这是否是您所期望的。首先,我之前从未听说过 sprint-boot,对此我感到非常抱歉。但是在使用 JavaScript 下载文件时,我总是使用这种方法。此方法直接从浏览器下载带有 blob 的文件。
代码:
//saving and downloading a file with a js blob;
function downloadFile(data, filename, type) {
var file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, filename); //IE 10+
} else {
var a = document.createElement("a");
var url = window.URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
我从这个问题中得到了这个代码: JavaScript:创建和保存文件
推荐阅读
- python - python,如何删除print的序列号?
- snowflake-cloud-data-platform - 雪花行访问策略权限
- reactjs - 如何使用 Jest 和 React 测试库测试功能性 React 组件的 clickHandler?
- angular - ngx-permissions formbuilder 禁用输入
- php - Moodle 数据表
- python - 如何为每年三个班级的百分比制作堆积条形图?
- python - 如何创建一个持续接受用户输入并评估所有输入的程序
- windows - 通过管道将 CMD 输出传递给 Powershell
- user-interface - 关闭除 tkinter 中的启动窗口以外的所有窗口
- python - 如何使用if条件合并两个数据框