Angular 2 Best approach to use FileSaver.js

后端 未结 4 1166
说谎
说谎 2020-12-09 09:31

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 w

相关标签:
4条回答
  • 2020-12-09 10:03

    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.

    0 讨论(0)
  • 2020-12-09 10:12

    Just doing npm install file-saver --save is a good start. You also need a typescript declaration file (like file-saver.d.ts or typings.d.ts) for this library is in plain javascript. Normally you would get it by doing npm install @types/file-saver but this package is currently outdated.

    I have created a file-saver.d.ts for myself – just place it in your source directory.

    file-saver.d.ts

    declare function saveAs(data: Blob, filename: string, noAutoBOM?: boolean): void;
    declare module 'file-saver' {
        export = saveAs;
    }
    

    Then you can use saveAs as follows:

    your.ts

    import saveAs = require('file-saver');
    function save() {
        let blob = new Blob(['Hello world!'], { type: 'text/plain;charset=utf-8' });
        saveAs(blob, 'newcontrol.txt');
    }
    

    Of course, don't forget to update your loader's configuration.

    For SystemJS you need something like this:

    /**
     * System configuration for Angular samples
     * Adjust as necessary for your application needs.
     */
    (function (global) {
      System.config({
        paths: {
          // paths serve as alias
          'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
          // our app is within the app folder
          app: 'app',
    
          // angular bundles
          '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
          '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
          '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
          '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
          '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
          '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
          '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
          '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
    
          // other libraries
          'rxjs':                      'npm:rxjs',
          'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
          'file-saver':                'npm:file-saver'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
          app: {
            main: './main.js',
            defaultExtension: 'js'
          },
          rxjs: {
            defaultExtension: 'js'
          },
          'file-saver': {
            main: './FileSaver.js',
            defaultExtension: 'js'
          }
        }
      });
    })(this);
    
    0 讨论(0)
  • 2020-12-09 10:13

    Even not a great way like other people mentioned, I prefer to use existing package from NPM which called ngx-filesaver. It is even works fine with Angular Universal.

    Just do:

    npm install file-saver ngx-filesaver --save


    Include to your Module project:

    ...
    import { FileSaverModule } from 'ngx-filesaver';
    ...
    @NgModule({
      imports: [ FileSaverModule ]
    })
    ...
    


    Then load the service to your component:

    ....
    import {FileSaverService} from 'ngx-filesaver';
    ...
    
    @Component({
        ...
    })
    ...
    constructor(Http, private fileSaverService: FileSaverService) {
    }
    
    onSave() {
     workbook.xlsx.writeBuffer()
          .then( (buffer) => {
    
            //I am saving spreadsheed ( XLSX ) buffer here...
            this.fileSaverService.save(new Blob([buffer], { type: 'application/octet-stream'}), `${fileName}.xlsx`);
    
          });
    }
    

    More detail please visit: https://www.npmjs.com/package/ngx-filesaver

    0 讨论(0)
  • 2020-12-09 10:21

    If you're using Angular-CLI to build your project, you can install it by running

    npm install file-saver --save
    

    Since there aren't any typings for FileSaver, I had to do:

    declare module "file-saver";
    

    in my typings.d.ts file.

    Then, to use it:

    // Import
    import * as FileSaver from "file-saver";
    
    //Implementation
    FileSaver.saveAs(blob, filename);
    

    For reference, these steps are taken from Angular-Cli's steps for installing third-party libraries

    Edit 9/27/2017: It appears there is now a type definition for FileSaver.js according to the README instructions, so instead of the

    declare module "file-saver"
    

    you just need to

    npm install @types/file-saver --save-dev
    
    0 讨论(0)
提交回复
热议问题