Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 HttpModule How to Return a File From Get Request

Tags:

angular

I have a REST API that if I query directly in the browser, it returns a JSON or CSV file to download. I want to do the same thing with the Angular HttpModule.

My get request is simple (it has a query string param to indicate which file format to return):

public Submit(request: Request) {
  ...
  return this.http.get(url).subscribe(response => {
    //What here
  });
}

The response content-type is application/octet-stream. I've tried processing the response as a blob, which doesn't work. How can I just pass through the response from the server to the browser and let it download the file? This method is part of a service that is being called by a component that is responding to a button click

onClick() {
    this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file
}
like image 293
mhaken Avatar asked Aug 19 '26 20:08

mhaken


1 Answers

You have to add

{ responseType: ResponseContentType.Blob }

and then map response to blob.

return this.http.get(url, { responseType: ResponseContentType.Blob })
    .map(r => r.blob())
    .subscribe(response => {

    });

Next you can download this file using fileSaver.js.

like image 94
Michał Ochociński Avatar answered Aug 25 '26 06:08

Michał Ochociński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!