8

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

enter image description here

Edit:

When I try to open the downloaded file, see below image enter image description here enter image description here

Can someone help me on this?

iLaYa ツ
  • 3,941
  • 3
  • 32
  • 48
  • You are showing us a console.log result but do not show the call... So it's hard to say. But looking at the log, it seems about the right content, why are you saying it is corrupt? – Salketer Aug 09 '17 at 09:05
  • @Salketer I updated the question. Please see if it helps. I can post API call also if you want. – iLaYa ツ Aug 09 '17 at 09:12
  • ok, try decompressing the file (treat it as a .zip) if it works, it means it is not corrupt but there was a problem when the file was generated. This can happen if an XML part is missing, or some parameters are not set correctly. – Salketer Aug 09 '17 at 09:19
  • 1
    Also, you could try to use a known-to-be-good file just to test your download code first... – Salketer Aug 09 '17 at 09:19
  • You have the solution now@iLaYaツ – Navi Jul 30 '21 at 10:13

1 Answers1

19

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'});
SOS
  • 6,430
  • 2
  • 11
  • 29
Steven Monteiro
  • 306
  • 3
  • 6