3

I want to download file from my Rest API with FileSaver. In response headers in Content-Disposition I have filename. How can I read header in angular? When I set my service like this:

getPdf() {
return this.httpClient.get(this.url, {responseType: 'blob'}); } 

I can download file without any problems, but when I want to set additionally {observe: 'response'} to read header in options I have error in my browser.

ERROR TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
at saveAs (FileSaver.js:112)

My function to save file:

this.packageService.getPdf().subscribe(
  pdf => {
     saveAs(pdf);
  }
);

I added Access-Control-Expose-Headers on my backend, only when i added {observe} there is an error so i can't find solution for this one.

  • on your backend, what is the url you are trying to hit? right now you are trying to do something like `localhost:8080/url` because you are passing in `'url'` ant not `this.url`. Also, have you checked out this answer https://stackoverflow.com/a/33759534/8947748 – rhavelka Nov 21 '19 at 16:46
  • sorry my mistake, there is this.url, and my url is localhost:8080/packages/{id}/raport, but there is no problem, because my problem shows when i want to read headers with {observe}. Without it file is downloading normally. – Adrian Jaczyński Nov 21 '19 at 16:50

1 Answers1

0

I think the problem is, when you request a response, it's not just data. So, when you are trying to directly pass it to filesaver it throws an exception.

I think this might work?

this.packageService.getPdf().subscribe(
  response => {
     saveAs(response.body);
  }
);
Fulya D.
  • 592
  • 4
  • 9
  • There isn't response.body (Property does not exist on type Blob). This code that i wrote is working and file is downloading, but I can't get headers from response. This error is showing when i add {observe: 'response'} in my service. Without it everything is fine. – Adrian Jaczyński Nov 21 '19 at 17:05
  • I am not sure what is the problem, since I can't replicate the exact problem. But when I set my get method like this, I can read the header: getPdf() { return this.httpClient.get(url, { observe: "response", responseType: "blob"}); } – Fulya D. Nov 21 '19 at 18:05
  • 1
    Also, there is this answer https://stackoverflow.com/a/50887300/10934321 – Fulya D. Nov 21 '19 at 18:08
  • Okay I find an error. I was importing saveAs from 'file-saver/dist/FileSaver' not from 'file-saver' and this was producing error... Thank you for help. – Adrian Jaczyński Nov 21 '19 at 18:32