close

How do I download a file with Angular2 or greater

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How do I download a file with Angular2 or greater in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How do I download a file with Angular2 or greater ?

  1. How do I download a file with Angular2 or greater ?

    do I download a file with Angular2 or greater Update to Hector's answer using file-saver and HttpClient for step 2:
    public downloadFile(file: File): Observable<Blob> { return this.http.get(file.fullPath, {responseType: 'blob'}) }

  2. How do I download a file with Angular2 or greater ?

    do I download a file with Angular2 or greater Update to Hector's answer using file-saver and HttpClient for step 2:
    public downloadFile(file: File): Observable<Blob> { return this.http.get(file.fullPath, {responseType: 'blob'}) }

Method 1

The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.

One of the many ways that exist to solve this is as follows:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                 error => console.log('Error downloading the file.'),
                 () => console.info('OK');

When the request is ready it will call the function “downloadFile” that is defined as follows:

downloadFile(data: Response) {
  const blob = new Blob([data], { type: 'text/csv' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}

the blob has been created perfectly and so the URL var, if doesn’t open the new window please check that you have already imported ‘rxjs/Rx’ ;

  import 'rxjs/Rx' ;

I hope this can help you.

Method 2

Update to Hector’s answer using file-saver and HttpClient for step 2:

public downloadFile(file: File): Observable<Blob> {
    return this.http.get(file.fullPath, {responseType: 'blob'})
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment