javascript - 使用 javascript 和 spring boot 下载文件

标签 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 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/

相关文章:

java - 在 Java 中实现去抖动

java - 从 JOptionPane.showMessageDialog 上的自定义 JButton 返回值

java - 如何使用Java修复外部MongoDB的 "MongoSocketException"?

java - 如何一次查询所有/执行器/指标?

javascript - 如何使用下划线创建自己的可继承类

javascript - 单独的 css 和 javascript 的谷歌示例失败

javascript - 选中两个复选框时背景颜色如何变化

javafx - 部分可编辑的表格 View

java - 避免代码重复 Spring Boot Controller

javascript - 移动导航在调整大小时定位不正确