Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I download a file with Angular2 or greater

People also ask

How do I download a javascript file?

To ask the browser to download a file it can render, use the following header: Content-Disposition: attachment; filename="downloaded. pdf" (you can of course customize the filename as you need).

How do I download a data file from a website?

Go to the webpage where you want to download the file. Save the file: Most files: Click on the download link. Or, right-click on the file and choose Save as.

How do I download files or data?

You can usually download a file by clicking a link that says Download or a down-arrow icon. Downloaded files are saved to your computer, phone, or tablet's Downloads folder by default. To download a photo from the web, right-click the photo and choose the Save option.


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.


Try this!

1 - Install dependencies for show save/open file pop-up

npm install file-saver --save
npm install -D @types/file-saver

2- Create a service with this function to recive the data

downloadFile(id): Observable<Blob> {
    let options = new RequestOptions({responseType: ResponseContentType.Blob });
    return this.http.get(this._baseUrl + '/' + id, options)
        .map(res => res.blob())
        .catch(this.handleError)
}

3- In the component parse the blob with 'file-saver'

import {saveAs as importedSaveAs} from "file-saver";

  this.myService.downloadFile(this.id).subscribe(blob => {
            importedSaveAs(blob, this.fileName);
        }
    )

This works for me!


If you don't need to add headers in the request, to download a file in Angular2 you can do a simple (KISS PRINCIPLE):

window.location.href='http://example.com/myuri/report?param=x';

in your component.


This is for folks looking how to do it using HttpClient and file-saver:

  1. Install file-saver

npm install file-saver --save

npm install @types/file-saver --save

API Service class:

export() {
    return this.http.get(this.download_endpoint, 
        {responseType: 'blob'});
}

Component:

import { saveAs } from 'file-saver';
exportPdf() {
    this.api_service.export().subscribe(data => saveAs(data, `pdf report.pdf`));
}