user2304483
user2304483

Reputation: 1644

How to use FileSaver in angular 5 correctly?

I'm trying to save file to file system using file upload functionality. Since the file is require for the angular app and not for the backend (rest api - java), I decided to save it in the frontend app which means somewhere inside the assets folder in angular app.

I've install angular-file-saver.

Template code:

<input type="file" name="file-7[]" id="file-7" class="inputfile inputfile-6" (change)="handleFileInput($event.target.files)">

component code:

import { FileSaver }  from 'angular-file-saver';

handleFileInput(files: FileList) {
    this.imageUpload = files.item(0);
    this.imageFileName = this.logoToUpload.name;
    // how to use FileSaver here ? 
    //this.imageUpload doesn't have data or something like this 

  }

Any idea how to actually save the file in a folder ? thanks.

Upvotes: 6

Views: 55459

Answers (3)

Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10862

To trigger the broswer saveAs using angular start by installing these packages

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

Add the FileSaverModule module to your project:

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

Then in your component/service

//if you have issues with this line you might need to stop ng serve and relaunch it
import { FileSaverService } from 'ngx-filesaver'; 

browserSaveAs(blob: any, filename:string) {
    try {
      this.fileSaverService.save(blob, filename);
    }
    catch (e)
    {
      console.log(e) ;
    }
}

The blob can be text content, image, etc.

Upvotes: 5

Or Zohar
Or Zohar

Reputation: 61

for encoding in a different language create blob like this:

var blob = new Blob(["\ufeff"+csvArray], { type: 'text/csv;charset=utf-8' })

Upvotes: 4

Barr J
Barr J

Reputation: 10927

The simple syntax is:

  vm.download = function(text) {
    var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
    FileSaver.saveAs(data, 'text.txt');
  };
}

notice the FileSaver.saveAs() method, which accepts Blob as parameter.

In your case it might look like:

handleFileInput(files: FileList) {
    this.imageUpload = files.item(0);
    this.imageFileName = this.logoToUpload.name;
    // how to use FileSaver here ? 
    var data = new Blob([imageUpload], { //your file type here });
    FileSaver.saveAs(data, this.imageFileName);  
  }

Note, you might as well need to convert the image to 64 bit and back again from 64 bit in order to save and display it

full example can be found at anguler-file-saver npm page.

Upvotes: 4

Related Questions