Uploading any File (.pdf, .epub , .docx, & More) to Firebase


#1

This works in Ionic 2 & 3 incase you’re wondering.
In your page.ts, to upload the files, put:


import {FileChooser} from '@ionic-native/file-chooser';
import {FilePath} from '@ionic-native/file-path';
declare var cordova: any;
/* If you want the file opening in browser to automatically download please install 
the in app browser plugin 

cordova plugin add cordova-plugin-inappbrowser

*/
constructor(
     public FilePath:FilePath,
    public FileChooser:FileChooser,
    public eventsdata: EventData,
// Other things...
){

// Code..

} 
 selectFile(){
let file
    this.FileChooser.open().then((uri) => {
     this.FilePath.resolveNativePath(uri).then((fileentry) => {
       let filename = this.eventsdata.getfilename(fileentry);
       let fileext = this.eventsdata.getfileext(fileentry);
      
       if(fileext == "pdf"){
          this.eventsdata.makeFileIntoBlob(fileentry, fileext,"application/pdf").then((fileblob) => {
            file={
               blob : fileblob,
              type: "application/pdf",
              fileext: fileext,
              filename: filename
            }
            this.eventsdata.addAssignmentFile(this.sbaid.sbaid, file)
      })
       }
         if(fileext == "docx"){
          this.eventsdata.makeFileIntoBlob(fileentry, fileext,"application/vnd.openxmlformats-officedocument.wordprocessingml.document").then((fileblob) => {
       file={
               blob : fileblob,
              type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
              fileext: fileext,
              filename: filename
            }
            this.eventsdata.addAssignmentFile(this.sbaid.sbaid, file)
      })
       } 
         if(fileext == "doc"){
          this.eventsdata.makeFileIntoBlob(fileentry, fileext,"application/msword").then((fileblob) => {
            file={
               blob : fileblob,
              type: "application/msword",
              fileext: fileext,
              filename: filename
            }
            this.eventsdata.addAssignmentFile(this.sbaid.sbaid, file)
        })
       }
       if(fileext == "epub"){
          this.eventsdata.makeFileIntoBlob(fileentry, fileext,"application/octet-stream").then((fileblob) => {
         file={
               blob : fileblob,
              type: "application/octet-stream",
              fileext: fileext,
              filename: filename
            }
            this.eventsdata.addAssignmentFile(this.sbaid.sbaid, file)
        })
       }
          if(fileext == "accdb"){
          this.eventsdata.makeFileIntoBlob(fileentry, filename,"application/msaccess").then((fileblob) => {
         file={
               blob : fileblob,
              type: "application/msaccess",
              fileext: fileext,
              filename: filename
            }
            this.eventsdata.addAssignmentFile(this.sbaid.sbaid, file)
        })
       }
         if(fileext == "xlsx"){
          this.eventsdata.makeFileIntoBlob(fileentry, filename,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").then((fileblob) => {
         file={
               blob : fileblob,
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              fileext: fileext,
              filename: filename
            }
            this.eventsdata.addAssignmentFile(this.sbaid.sbaid, file)
        })
       }

 //      else if (fileext!="doc"||"epub"||"xlsx"||"pdf"||"accdb"||"docx" ){

 //alert("Can't add "+  filename)

 //      }
      
      })
    })
}

  gotoFilePage(file){
cordova.InAppBrowser.open(file,"_system", "location=yes");
  }

Now, you’ll need a list of the files from firebase from after they’re uploaded so, The following code goes inside your constructor() to load the list.


     this.eventsdata.getRequestFiles().on('value', snapshot => {
      let rawList = [];
      snapshot.forEach(snap => {
        rawList.unshift({
          id: snap.key,
          file: snap.val().file,
          name: snap.val().name,
          ext: snap.val().ext,
        })
      })
      this.files = rawList;
      this.filesnum = rawList.length
    });

In page.html (Dont forget to wrap around an ion-content)

<ion-item text-wrap (click)="selectFile()">
   
    <button  item-left ion-fab color="primary"><ion-icon name="list-box"></ion-icon></button>
  <h3>  Add File  </h3>
  <p > Quickly add another file to your assignment</p>
   
  </ion-item>

<div *ngIf="filesnum >0">
  <ion-item  (click)="gotoFilePage(file.file)"  *ngFor="let file of files">
<h3> {{file.name}}</h3>
<button clear ion-button icon-only item-right><ion-icon name="download" color="danger"></ion-icon></button>
</ion-item>
</div>


eventsdata is my provider with the firebase code. This is what’s happening there.

import firebase from 'firebase';

export class EventData {

  sbaList:any;

  constructor() {
    this.sbaList = firebase.database().ref('/sbalist');
  }
 makeFileIntoBlob(_imagePath, name, type) {

  // INSTALL PLUGIN - cordova plugin add cordova-plugin-file
  return new Promise((resolve, reject) => {
    window.resolveLocalFileSystemURL(_imagePath, (fileEntry) => {

      fileEntry.file((resFile) => {

        var reader = new FileReader();
        reader.onloadend = (evt: any) => {
          var imgBlob: any = new Blob([evt.target.result], { type: type });
          imgBlob.name = name;
          resolve(imgBlob);
        };

        reader.onerror = (e) => {
         alert('Failed file read: ' + e.toString());
          reject(e);
        };

        reader.readAsArrayBuffer(resFile);
      });
    });
  });
}

getfilename(filestring){

   let file 
   file = filestring.replace(/^.*[\\\/]/, '')
   return file;
}

getfileext(filestring){
  let file = filestring.substr(filestring.lastIndexOf('.') + 1);
   return file;
}
getRequestFiles(sbaid): any {

   return this.sbaList.child('sbafiles');

  }

 addAssignmentFile(sbaid, file:any):any{

    return   this.sbaList.child(file.filename)
//Saves the file to storage
          .put(file.blob,{contentType:file.type}).then((savedFile) => {
//Gets the file url and saves it in the database
               this.sbaList.child('sbafiles').push({
               file: savedFile.downloadURL,
               name: file.filename,
               ext: file.fileext,
               type: file.type
          });
      })

  }

And it should work for you after customizing it to fit your needs.


Upload file to firebase -- FileChooser
#2

Can I get some feedback as to if this was straight forward enough?


#3

Looks to me like you’re reinventing both the angularfire and ionic-native wheels, but whatever works for you, I guess.


#4

This is really suit my need for my Chat application, it work perfectly. Thanks a lot for sharing this with for the community. Appreciate your effort.


#5

@trevaun23 from where did you get the EventData plugin there is no such a plug in or perhaps i could not found if you have please share

thank you !!!


#6

Hey hiyat. It’s a custom provider I made.

In your cli run : ionic g provider EventData

That will make an event-data.ts file in the providers folder.

Then paste in the code I shared for the “event-data.ts” file.

And everything should work.

*you may need to change the path in your page.ts if the “event-data.ts” provider is made inside an “event-data” folder.


#7

@trevaun23 oh yah thank you very much your post was really helpful :blush:


#8

Can i get the full source code ?


#9

Hi! @trevaun23 im making a project to upload/download a pdf file to firebase, i want to run on android/ios/browser but im having troubles, can you give me a hand. It’s posible to read your entire code?

sorry my poor english!


#10

this.FilePath.resolveNativePath(uri) is throwing an error “_data column does not exist”. How to resolve that problem?