Use Filesaver js with angular2
Solution 1
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.
Solution 2
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'
})
}
Solution 3
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');
});
mayowa ogundele
I am currently a software developer in one of the leading Banks in Africa with experience in MVC, Entity Framework, LINQ, SQL Server, ASP.Net and other web technologies.
Updated on February 06, 2020Comments
-
mayowa ogundele about 4 years
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?
-
mayowa ogundele over 7 yearsThanks it worked. i imported the wrong library in the first place
-
Ng2-Fun about 7 years@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? -
dipole about 7 years@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.
-
Ng2-Fun about 7 yearsHi @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.
-
jvhang about 7 years@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.
-
makkasi over 6 years@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'
-
MikeOne over 5 yearsThis doesn't work for me. "export 'saveAs' was not found in 'file-saver'.