这是我的 JavaScript 代码:
$('#downloadTraining').on('click', function () {
$.get(restbase() + "/download-training/" + $('[name=trainingId]').val()).done(function(data) {
}).fail(function(data) {
errorAlert();
}).always(function(data) {
});
});
这是我的 Spring Boot Controller 方法:
@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 中的错误吗?
响应和请求 header :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: Create and save file
关于javascript - 使用 javascript 和 spring boot 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53243976/