I have a web service that returns an HTTP response with the following Content-Type:
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
When I call this service using cURL and redirect the output to create a .xlsx file, everything works perfectly. However, when I try to save the file from JavaScript, it fails. Here is the code snippet I am using:
cURL:
$ curl -v -X POST <API_ENDPOINT> > a.xlsx ;# a.xlsx works fine
Javascript:
$http.post(<API_ENDPOINT>).then(function(response) {
console.log(response);
downloadFile(response.data, "b.xlsx")
});
var downloadFile = function(responseData, fileName) {
var blob = new Blob([responseData], {
type: 'application/vnd.ms-excel'
});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
document.body.appendChild(a);
a.style = 'display: none';
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
};
Although the file gets saved, the contents appear to be different from the one downloaded via cURL, even though the server sends the same file.
The content-length
header value is consistent in both responses (cURL and JavaScript captured through Chrome DevTools), but the file size when redirected via cURL is 5.1k (almost matching the content-length
value), while the file size of the file created by JavaScript is 8.5k, which is incorrect.
I have tried setting various content types like application/octet-stream
, octet/stream
,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
when creating the blob, but none seem to resolve the issue.
I suspect that there may be something wrong with how I handle the content-type and blob creation, but I cannot pinpoint the exact problem. Any assistance would be greatly appreciated.