Use Filesaver js with angular2

流过昼夜 提交于 2019-11-29 10:49:11

Try the following

npm install file-saver --save

Then add a declarations file to your project like 'declarations.d.ts' and in it put

declare module 'file-saver';

In your systemjs.config.js, add the following to the map section

'file-saver': 'npm:file-saver/FileSaver.js'

And then import the library in your component or service like below

import { Component } from '@angular/core';
import * as saveAs from 'file-saver';


@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <button (click)="SaveDemo()">Save File</button>`,
})
export class AppComponent {
  name = 'Angular';

  SaveDemo() {
    let file = new Blob(['hello world'], { type: 'text/csv;charset=utf-8' });
    saveAs(file, 'helloworld.csv')
  }
} 

Hope it helps.

For angular-cli with http (followed by httpClient):

npm install file-saver --save

Add this third party lib to .angular-cli.json

"scripts": [
      "../node_modules/file-saver/FileSaver.js"
    ],

In the blabla service:

downloadBlaBlasCSV() {
        let options = {responseType: ResponseContentType.ArrayBuffer };
        return this.http.get(this.config.apiUrl + '/blablasCSV', options)
        .catch((err: Response) => Observable.throw(err.json()));
    }

Finally int the component:

import { saveAs } from 'file-saver';

downloadBlaBlasCSV() {
    this.blablaService.downloadBlaBlasCSV().subscribe(
      (data) => { this.openFileForDownload(data); },
      (error: any) => {
        ...
      });
  }

openFileForDownload(data: Response) {
    //var blob = new Blob([data._body], { type: 'text/csv;charset=utf-8' });
    //saveAs(blob, 'Some.csv');
    let content_type = data.headers.get('Content-type');
    let x_filename = data.headers.get('x-filename');
    saveAs(data.blob(), x_filename);
  }

httpClient

It's the same like http but the service method is different:

downloadBlaBlasCSV() {
        return this.httpClient.get(this.config.apiUrl + '/blablasCSV',  {
            headers: new HttpHeaders().set('Accept', 'text/csv' ),
            observe: 'response',
            responseType: 'blob'
        })
    }

I am using angular 6 (no systemjs.config.js file available in my project) + FileSaver. I needed to download PDF from server. Here is what worked:

npm install file-saver --save

package.json:

"file-saver": "^1.3.8"

code:

import { saveAs } from 'file-saver';
...
this.http
      .get<any>("/pdfs/mypdf.pdf", { responseType: 'blob' as 'json' })
      .pipe(
        tap(deployments => this.log(`fetched resoure`)),
        catchError(this.handleError('getResource', []))
      )
      .subscribe(data => {
        console.log(data);
        saveAs(new Blob([data], { type: 'pdf' }), 'data.pdf');
      });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!