How can i able to convert pdf, xlsx and doc file in base64 data in ionic 3?

Viewed 231

My code is:

addFilesforRNAppz(inputFile: any) {
 const fileget = this.fileInputVariable.nativeElement.files;

 let fileList: FileList = inputFile.target.files;

 // I can access the selected file name, size and object correctly without any issues
 console.log("File name = " + fileList[0].name);
 console.log("File size = " + fileList[0].size);
 console.log("File = " + fileList[0]);

 // Converting the file input to base 64 (This rarely works)
 this.convertFileToBase64AndSet(fileList);

 // ===============================================================
}
convertFileToBase64AndSet(fileList: FileList)
{
   if(fileList.length > 0)
  {
    var reader = new FileReader();

      reader.onloadend = (e: Event) => {

      console.log(reader.result);
    }

    reader.readAsDataURL(fileList[0]);
  }
}


<input type="file" #inputFile (change)="addFilesforRNAppz($event)" class="file-input" />

I want base64 data of selected pdf or any doc file. I can be convert Image into base64, but it does not convert from pdf to base64 data.

what is the problem in my code, please give any solution as soon as possible, it would be really appreciated.

2 Answers

I can be convert Image into base64, but it does not convert from pdf to base64 data.

Your reading code will work the same for img or pdf or anything else. However I suspect you are trying to use the read value as a data-uri src. That will not work for pdf files and will only work for images.

To convert pdf you can use :

file.readAsArrayBuffer(filePath, fileName)

Following is the complete code for reading pdf which is got by filechooser plugin:

this.fileChooser.open().then((uri) => {
       this.filePath.resolveNativePath(uri).then((finalUri) => {
         this.file.resolveLocalFilesystemUrl(finalUri).then((entry) => {
          let filePath = entry.nativeURL.substring(0, entry.nativeURL.lastIndexOf('/'));
          if (entry.name.endsWith('.pdf')){
            return this.file.readAsArrayBuffer(filePath, entry.name)
              .then((data) => {
                //data after reading pdf
              })
              .catch((error) => {
                //error
              });
          }
        })
      })
    })
Related