boden
boden

Reputation: 1681

Downloaded by ajax excel file is corrupted

I have a Spring Boot web application, which generate Microsoft Excel file with extention .xlsx.

If I try to download file from browser calling the localhost:8080/report/stats it a returns correct file and I always can open it one successfully.

But, when I download a file from web page by click on button I get a bad file and I can't open it one.

I have the following part on 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();
    }
});

Controller:

@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);
}

Why downloading from browser works well and not works from JS?

Open file error:

Open file error

YES has been clicked:

enter image description here

NO has need clicked:

enter image description here

Upvotes: 2

Views: 2220

Answers (1)

boden
boden

Reputation: 1681

I was able to download a valid file using the following code

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

Upvotes: 1

Related Questions