Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Best approach to use FileSaver.js

Tags:

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 page and it will work. But I was wondering what would be the best approach in case of an Angular 2 (TypeScript) application so that I can just call window.saveAs to save file.

like image 223
Naveed Ahmed Avatar asked Oct 25 '16 13:10

Naveed Ahmed


People also ask

How do I use angular FileSaver?

Basic usage Include ngFileSaver module into your project; Pass both FileSaver and Blob services as dependencies; Create a Blob object by passing an array with data as the first argument and an object with set of options as the second one: new Blob(['text'], { type: 'text/plain;charset=utf-8' }) ; Invoke FileSaver.

What is FileSaver in angular?

FileSaver. js is the solution to saving files on the client-side, and is perfect for web apps that generates files on the client, However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatiblity.

How do I import FileSaver?

You can npm install file-saver, then point to the node_modules FileSaver. js file in the <script> tag. Save this answer. Show activity on this post.

What is file saver?

The File Saver component enables you to save files on the client machine. The saving of files is done through the saveAs method. You can consume the package from TypeScript and JavaScript projects alike.


1 Answers

I managed to get it work using this approach (Angular-CLI):

npm install file-saver --save npm install @types/file-saver --save 

After that import Filesaver in component:

import * as FileSaver from 'file-saver'; 

And you can use it like this:

    let blob = new Blob([document.getElementById('exportDiv').innerHTML], {             type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-16le"         });     FileSaver.saveAs(blob, "export.xls");     

As you can see, you don't have to add anything in angular-cli.json. Just install library and it's types, import it and you are ready to go.

like image 129
Tomislav Avatar answered Oct 06 '22 07:10

Tomislav