[英]Download file using java script and spring boot
This is my javascript code : 这是我的JavaScript代码:
$('#downloadTraining').on('click', function () {
$.get(restbase() + "/download-training/" + $('[name=trainingId]').val()).done(function(data) {
}).fail(function(data) {
errorAlert();
}).always(function(data) {
});
});
And this is my spring boot controller method : 这是我的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);
}
Calling get method from javascript is working. 从javascript调用get方法正在工作。 Getting file is working.
正在获取文件。 But it doesn't download file.
但是它不会下载文件。 Is there anything i need to add to javascript or error is in Java ?
有什么我需要添加到javascript或Java中的错误吗?
Response and request headers : http://prntscr.com/lh01zx 响应和请求标头: http : //prntscr.com/lh01zx
I have a solution but I don't know if this is what you are expecting. 我有一个解决方案,但我不知道这是否是您所期望的。 Firstly I have never heard of sprint-boot before so sorry about that.
首先,在此之前我从未听说过sprint-boot。 But when it comes to downloading files with JavaScript I always use this method.
但是在使用JavaScript下载文件时,我总是使用此方法。 This method downloads files with a blob and directly from the browser.
此方法直接从浏览器下载带有斑点的文件。
code: 码:
//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);
}
}
I got this code from this question: 我从以下问题得到此代码: JavaScript: Create and save file
JavaScript:创建并保存文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.