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?

3 Answers 3

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.

5
  • Thanks it worked. i imported the wrong library in the first place Nov 25, 2016 at 7: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, 2017 at 2: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, 2017 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, 2017 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, 2017 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'
        })
    }
1
  • @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, 2017 at 7: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');
      });
1
  • This doesn't work for me. "export 'saveAs' was not found in 'file-saver'.
    – MikeOne
    Sep 27, 2018 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.