I'm trying to download a xlsx file which is generated in the java backend from the angular frontend and I'm getting file as an attachment with Content-Disposition header and I'm able to download the file with the below js code, but when I try to open it, it's always corrupted
var data = response; //from server
var blob = new Blob([data], { type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml;charset=UTF-8"});
var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'filname.xlsx';
link.click();
If I console log the server response, here is what I found
Edit:
When I try to open the downloaded file, see below image
Can someone help me on this?
Excel files can get corrupted if they were not saved properly, this could be because you did not shut down the program properly or if it shut down abruptly because of a power failure, hardware failure, or because of a virus or malware attack.
The following are common signs that your Excel file is corrupt. When you try to open your file and it fails to respond, there is a chance it is corrupt. Sometimes you may get the error message 'Unable to read file'. Another error you are likely to come across is 'Excel Cannot Open the File '(Filename)'.
On the File tab, click Open. In Excel 2013 or Excel 2016, click on the location where the spreadsheet is located, and click Browse. In the Open dialog box, select the corrupted workbook that you want to open. Click the arrow next to the Open button, and then click Open and Repair.
Choose Open from the File menu. In Excel 2007, click the Office button and select Open. Using the Look In control, locate and specify the corrupted workbook. From the Open button's dropdown list, shown in Figure A, choose Open And Repair.
I had this same issue with AngularJS 1.6.1. When I called my HTTP GET service from the browser or from window.open("url")
, the xlsx file was downloaded perfectly: 304628 bytes. However, the response.data
provided by AngularJS instead had 289414 bytes and the Blob wrapper had 550963 bytes, which is what is downloaded as a corrupted file. This same behavior occurred if I return the xlsx in a zip.
I solved this by setting the XMLHttpRequest.responseType
property as such:
$http.get(url, {responseType:'arraybuffer'});
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