I have a JavaScript app and an API that creates a Excel file and returns a byte array with the following headers:
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Content-Disposition:attachment; filename=List.xlsx
When I go the Excel resource API URL I'm prompted to download the Excel file. If I do so, it downloads fine and opens in Excel. All is good.
Now to the problem:
What I don't want is to expose the API URL in the user's browser window, so my goal is to:
What I have is this:
It downloads the file, but when I try to open the file, Excel doesn't recognize it as a valid Excel file.
// "data" is the contents from the server
var reader = new FileReader();
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
reader.readAsDataURL(blob);
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}
I got it working. I just had to add the following to my XMLHttpRequest object:
responseType: 'arraybuffer'
But it doesn't work in IE, because IE cannot open data URIs. Not even IE11.
Anyway I found a great library called FileSaver.js which handles saving files for all major browsers (including IE10+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With