Use Filesaver js with angular2

angular 6 file-saver
filesaver.js pdf example
angular 2 save file to disk
filesaver angularjs
filesaver.js cdn
angular 2 write text file
create text file in angular 6
xlsx file saver

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.

Can someone help please?

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.

Help needed in using fileSaver.js with Angular 2 app · Issue #308 , I am trying to use fileSaver.js with angular 2 , but am not able to import the module i am getting cannot find file-saver module error . Any help is  Can I use JS within my angular 2.x code. The fact that you are asking this question seems very . TypeScript is a superset of javascript and any javascript can be used in typescript but not the other way around.

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'
        })
    }

file-saver, FileSaver.js is the solution to saving files on the client-side, and is Using the application/octet-stream MIME type to force downloads can  First of all you need to add filesaver.js to your project. npm install file-saver --save..and add the typings npm install @types/file-saver --save-dev More information about filesaver you can find on the filesaver github pages. To download the file via http you need to implement a service. The following imports are required:

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');
      });

angular-file-saver, Basic usage. Include ngFileSaver module into your project;; Pass both FileSaver and Blob services as dependencies;; Create a Blob  Angular 2: File Saver. Ask Question Angular 2 Best approach to use FileSaver.js; Use Filesaver js with angular2; Angular2 FileSaver.js; share | improve this answer.

Implementing file save functionality with Angular 4 – Shekhar Gulati, how to implement this functionality in Angular 4 using FileSaver.js module. Step 1: Create an Angular 4 project I use Angular CLI to generate  Showing 8 changed files with 4,761 additions and 2,161 deletions. +32 −124 dist/angular-file-saver.bundle.js +1 −1 dist/angular-file-saver.bundle.min.js

angular-file-saver: Docs, Tutorials, Alternatives, I need to use the FileSaver.js (https://github.com/eligrey/FileSaver.js/) in my Angular2 application. I know I can add it as a script file in main html  In the latest filesaver documentation, an example is given for how to use filesaver.js in conjunction with blobbuilder.js: However blobbuilder.js has been deprecated and they now say to use blob.js (I can't find the code for blobbuilder.js anyway).

FileSaver.js demo, js and FileSaver.js polyfills via Blob and SaveAs services. Installation. # Using bower: $ bower install angular-file  Angular File Saver. Angular File Saver is an AngularJS service that leverages FileSaver.js and Blob.js to implement the HTML5 W3C saveAs() interface in browsers that do not natively support it.

Comments
  • Thanks it worked. i imported the wrong library in the first place
  • @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 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.
  • 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 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.
  • @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'
  • This doesn't work for me. "export 'saveAs' was not found in 'file-saver'.