【问题标题】:Downloaded by ajax excel file is corruptedajax下载的excel文件损坏
【发布时间】:2017-11-10 09:42:26
【问题描述】:

我有一个 Spring Boot Web 应用程序,它生成扩展名为 .xlsx 的 Microsoft Excel 文件。

如果我尝试从浏览器调用localhost:8080/report/stats 下载文件,它会返回正确的文件,我总是可以成功打开它。

但是,当我通过单击按钮从网页下载文件时,我得到了一个错误的文件,我无法打开它。

我在JS上有以下部分:

$.ajax({
    url: 'report/stats',
    type: "GET",
    success: function (data) {
        var link = document.createElement('a');
        link.download = 'report.xlsx';
        link.href = 'data:,' + data;
        link.click();
    }
});

控制器:

@GetMapping("stats")
public ResponseEntity downloadStatsReport() throws IOException {
    return fileResponse(excelReportService.create(new StatFilter()));
}

private ResponseEntity fileResponse(File report) throws IOException {
    InputStreamResource resource = new InputStreamResource(new FileInputStream(report));
    return ResponseEntity.ok()
            .contentLength(report.length())
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + report.getName())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

为什么从浏览器下载效果很好,而从 JS 下载不行?

打开文件错误:

YES已被点击:

没有需要点击:

【问题讨论】:

标签: javascript excel spring-boot


【解决方案1】:

我能够使用以下代码下载有效文件

function download(fileName) {
    window.location.href = "/download?description=test&logId=123";
}

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2012-02-23
    • 1970-01-01
    • 2014-09-01
    • 2016-01-19
    相关资源
    最近更新 更多