0

I am receiving the file contents from an API and i need to create a blob and download the file. I have written the below piece of code to do that -

const blob = new Blob([data], {type: filetype});
console.log("blob ", blob);
const elem = window.document.createElement('a');
console.log("element create ", elem);
  elem.href = window.URL.createObjectURL(blob); 
  console.log("elem.href ");
  elem.download = fileNameSplit[0];        
  document.body.appendChild(elem);
  elem.click();        
  document.body.removeChild(elem);

This works if the file is of txt format, but if it is of some different format like pptx or docx, the file gets downloaded but the data is corrupted so the file does not open. When i print the response from the API in the console, it loks like this -

response from API

How do download the correct format? I had faced this issue previously and i had solved it by changing the response type of the request i was sending to 'arraybuffer', but now i cannot do that since the structure of the API has changed.

I have tried the solutions in the following link - How do I read binary data to a byte array in Javascript? , but these are not working.

Any solution would be helpful. Thank you.

0 Answers0