Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Blob in Ionic

I am new to ionic framework, actually I am getting byte array as response from back end service and converting it to blob. How can I save it to PDF in ionic?

var blob = new Blob([res], { type: 'application/pdf' });

Here res is the response (byte array) from the service.

Code

var blob = new Blob([res], { type: 'application/pdf' });         

        let fileName="Receipt.pdf";         
        let filePath = (this.platform.is('android')) ? 
        this.file.externalRootDirectory : this.file.cacheDirectory;

        this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {

          console.log("File created!");          
          this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
            .then(() => console.log('File is opened'))
            .catch(err => console.error('Error openening file: ' + err));
        })
          .catch((err) => {
            console.error("Error creating file: " + err);
            throw err;  
          });

Thanks in advance.

like image 765
Kumar Avatar asked Dec 04 '17 14:12

Kumar


1 Answers

In order to SAVE the PDF, you'll need to use some cordova plugins. Ionic has some nice wrappers around these here. Check out the File, File Transfer, and File Opener plugins.

Here's some example code you could use once you get these plugins incorporated into your project:

    var blob = new Blob([res], { type: 'application/pdf' });

    //Determine a native file path to save to
    let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;

    //Write the file
    this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {

      console.log("File created!");

      //Open with File Opener plugin
      this.fileOpener.open(fileEntry.toURL(), data.type)
        .then(() => console.log('File is opened'))
        .catch(err => console.error('Error openening file: ' + err));
    })
      .catch((err) => {
        console.error("Error creating file: " + err);
        throw err;  //Rethrow - will be caught by caller
      });
like image 110
BRass Avatar answered Oct 05 '22 22:10

BRass