Download File in Angular4 using file-saver

Ravi Kukreja picture Ravi Kukreja · Mar 8, 2018 · Viewed 20.6k times · Source

I am trying to implement download file functionality in my angular 4 app. My api returns base 64 string of the file which I download from SharePoint. I am using file-saver module to get the file downloaded. Below is the code used.

let byteArray = new Uint8Array(res.data)
 , blob = new Blob([byteArray], {type: 'application/pdf'});
 saveAs(blob, "test.pdf");

res.data is the base64 string of file. The file gets downloaded, however, could not be opened. The error message is "file is corrupted or damaged". Text file gets downloaded and can be opened but is alway blank with no content. Am I doing something wrong.

Answer

Naoe picture Naoe · Mar 8, 2018

It's hard to know what is wrong without being able to test the actual request/response.

I would try to log the different objects and analyse the output, maybe cast the response directly to new Blob, and see what happens.

Another tips might be to test without using file-saver. Maybe something like this:

downloadFile(data: Response){
  var blob = new Blob([data], { type: 'application/pdf' });
  var url= window.URL.createObjectURL(blob);
  window.open(url);
}

Source: How do I download a file with Angular2