首页 > 解决方案 > 使用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

标签: javascriptjavaspring-boot

解决方案


我有一个解决方案,但我不知道这是否是您所期望的。首先,我之前从未听说过 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:创建和保存文件


推荐阅读