8

i have checked all the post i can find on the use of Filesaver JS with angular, but i still could not wrap my head around a soution. I added this to the map section of my system.config.js

 'filesaver': 'node_modules/filesaver/src/Filesaver.js'

I added this to the packages section of the system.config.js

  'filesaver': {defaultExtension: 'js'}

I then imported it in my service.ts this way

import { saveAs } from 'filesaver';

Yet i get this error.

enter image description here

Can someone help please?

Community
  • 1
  • 1
mayowa ogundele
  • 475
  • 2
  • 6
  • 19

3 Answers3

13

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.

dipole
  • 429
  • 4
  • 12
  • Thanks it worked. i imported the wrong library in the first place – mayowa ogundele Nov 25 '16 at 07:58
  • @dipole: From file-saver github page, it told us a way to install typescript definition `npm install @types/file-saver --save-dev`. Do I still need to add declarations file as you mentioned above? In my project root folder, I have an app folder and other files like systemjs.config.js files. If needed, where should I add it? Inside app folder or just under project root folder? – Ng2-Fun Mar 13 '17 at 02:44
  • @Ng2-Fun I wasn't able to get it to work with the typescript definition which is why I went the route of the declarations file. I kept getting "TypeError: file_saver_1.saveAs is not a function". You can place the declarations file in the project root folder. – dipole Mar 13 '17 at 23:02
  • 1
    Hi @dipole - I got the same error when using typescript definition. Then I followed exactly what you did, and got an error: saveAs is not a function. But finally I found there is an easy way to download file without using filesaver.js, instead, we can make http request and then call window.open() to download image. – Ng2-Fun Mar 14 '17 at 20:27
  • @Ng2-fun Same thing here. I worked around it by declaring: declare var saveAs:any; In my component, and referencing the file-saver js file directly in my html file. – jvhang Apr 12 '17 at 20:51
13

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'
        })
    }
makkasi
  • 6,328
  • 4
  • 45
  • 60
  • @DevStar You should add on server side the content type to the response. For python response.headers['Content-type'] = 'text/csv' or for Java response.setContentType("text/csv") ___________ Also there are some headers that are not send from the server sometime, and the server should explicitly expose them. In python _______response.headers["x-filename"] = filename _______response.headers["Access-Control-Expose-Headers"] = 'x-filename' – makkasi Oct 10 '17 at 07:31
1

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');
      });
Nitin Jadhav
  • 6,495
  • 1
  • 46
  • 48