簡體   English   中英

由ajax excel文件下載的文件已損壞

[英]Downloaded by ajax excel file is corrupted

我有一個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效果不好?

打開文件錯誤:

打開文件錯誤

單擊是:

在此處輸入圖片說明

無需點擊:

在此處輸入圖片說明

我可以使用以下代碼下載有效文件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM