繁体   English   中英

使用Java脚本和Spring Boot下载文件

[英]Download file using java script and 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 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中的错误吗?

响应和请求标头: http : //prntscr.com/lh01zx

我有一个解决方案,但我不知道这是否是您所期望的。 首先,在此之前我从未听说过sprint-boot。 但是在使用JavaScript下载文件时,我总是使用此方法。 此方法直接从浏览器下载带有斑点的文件。

码:

//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:创建并保存文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM