2

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
  • 8,684
  • 19
  • 37
  • 59
Joes Apzara
  • 23
  • 1
  • 5

2 Answers2

7

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,354
  • 2
  • 12
  • 28
Adrita Sharma
  • 19,704
  • 10
  • 55
  • 71
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,426
  • 15
  • 19