Ionic 2 - Save Blob PDF to localstorage

I have an ionic 2 app where I am downloading blob pdf and would like to save it to local storage. I’ve tried using the Corodova File to write to the directory however I am getting a typerror:

“Uncaught (in promise): Type Error TypeError at Object.checkArgs… module.exports.resolveLocalFileSystemURL)”

Here is the code I am running at the moment, appreciate any help on this on how I could get it working???

let headers: any;
    let params = {format: format};
    headers = this.authService.getHeaders();
    return this.http.get('URL_ADDRESS_GOES_HERE' , {responseType: ResponseContentType.Blob, headers: headers, params: params})
.subscribe(
    (res: any) => {

      let obj: any;
      let fileName: string;

      if (this.format === "PDF") {
        obj = new Blob([res.blob()], { type: 'application/pdf' })
        fileName = name + ".pdf";
      }    

      if (this.platform.is('cordova')) {
        // Mobile (Not working)
        this.file.writeFile(this.file.dataDirectory, fileName, obj); 
      }  else {
        // Web-browser (Working)
        FileSaver.saveAs(obj, fileName);
      }

    })

@karvanj
install File and File Opener plugin.

File plugin
ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file

File Opener plugin:
cordova plugin add cordova-plugin-file-opener2
npm install --save @ionic-native/file-opener

import { FileOpener } from '@ionic-native/file-opener’;
import { File } from ‘@ionic-native/file’;


constructor(private file: File, private fileOpener: FileOpener){

}

downloadBlobToPDF(){
let downloadPDF: any = ‘W0JFR0lOXQolUERGLTEuMgp6R1/V+d9KpBi3sCNzNh…….’
        fetch('data:application/pdf;base64,' + downloadPDF,
          {
            method: "GET"
          }).then(res => res.blob()).then(blob => {
            this.file.writeFile(this.file.externalApplicationStorageDirectory, 'statement.pdf', blob, { replace: true }).then(res => {
              this.fileOpener.open(
                res.toInternalURL(),
                'application/pdf'
              ).then((res) => {

              }).catch(err => {
                console.log(‘open error’)
              });
            }).catch(err => {
                  console.log(‘save error’)     
       });
          }).catch(err => {
                 console.log(‘error’)
          });
}

and add following lines in config.xml

  <preference name="AndroidPersistentFileLocation" value="Compatibility" />
  <preference name="AndroidExtraFilesystems" value="sdcard,cache" />
4 Likes

Thank you very much I will try this out. Also would this also work in Ionic Dev App?? I understand not all Cordova plugins are supported.

@karvanj
Instead of ionic cordova plugin add cordova-plugin-file try the following

ionic plugin add cordova-plugin-file

1 Like