Topic: How to download an Excel file returned by an Ajax call
Torroni pro asked 1 year ago
I have a button that sends an http Ajax request to download an Excel file. The server returns the binary Excel file with the following headers:
Content-Disposition: Attachment;Filename="SummaryReport.xlsx"
Content-Length: 3751
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
and the Chrome developer tools window show that the response contains the correct binary data, however Chrome does not download the file. Any idea?
Torroni pro answered 1 year ago
Found out the solution: I had to split the operation in 2 parts:
- clicking the button triggers the creation of the Excel file on the server and it adds an anchor element with a download link
- clicking the anchor element downloads the file
Torroni pro answered 1 year ago
for whomever is interested, this is how I've done it. HTML:
<div class="card-body">
<div class="row mb-4">
<div class="col-3">
<button id="createReport" type="button" class="btn btn-secondary me-3">Report</button>
</div>
<a class="d-none" href="orchestrator/createReport/SummaryReport.xlsx" download></a>
</div>
</div>
JS:
var request = new XMLHttpRequest();
request.open("GET", "orchestrator/createReport", true);
request.onreadystatechange = function () {
if (request.readyState == XMLHttpRequest.DONE) {
if (request.status == 200) {
document.querySelector("#tools a").click();
} else {
showMessage("danger", "Error retrieving Summary Report from server");
}
}
}
request.send();
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Resolved
- ForumUser: Pro
- Premium support: No
- Technology: MDB Standard
- MDB Version: MDB5 6.4.0
- Device: laptop
- Browser: Google Chrome Version 112.0.5615.121 (Official Build) (64-bit)
- OS: Windows 10 Enterprise 22H2
- Provided sample code: No
- Provided link: No