3

I'm creating a webpage that has to download a file in CSV format. The REST API returns the file.

I get an error while accessing the API. I guess that is because the file is getting converted to JSON. How can I get it from the back end and handle it?

service.ts

return this.http.get(URL);             
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Joes Apzara
  • 33
  • 1
  • 5

2 Answers2

8

You can use file-saver

import * as FileSaver from 'file-saver';

this.http.post(url, resource, { responseType: 'blob' })
 .subscribe((resp: any) => {
    FileSaver.saveAs(resp, `filename.csv`)
 });
Mustapha Larhrouch
  • 3,373
  • 3
  • 14
  • 28
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

To convert octet-stream to any required data type.
I had a similar situation where i converted OCTET-STREAM into pdf.

Slight difference, might be helpful for others, I received json response and octet-stream Array was a field in that json response.

In this case, replace .pdf by .csv

octet_array is the array of octet values.

  let arr = new Uint8Array(octet_array);
        let downloadLink = document.createElement('a');
        let b = new Blob([arr], { type: 'application/octet-stream' })
        downloadLink.href = window.URL.createObjectURL(b);
        downloadLink.setAttribute('download', "prescription.pdf");
        document.body.appendChild(downloadLink);
        downloadLink.click();
        downloadLink.parentNode.removeChild(downloadLink);
Nabin Kumar Khatiwada
  • 1,546
  • 18
  • 19