Get File, turn into Blob, Upload to Firebase

So, I’m attempting to get a file, turn it into a blob from base64 and upload it to firebase.

This is what I have so far… Not working:

   chooseFile(){

  let blob
 FileChooser.open().then((uri) => {
   Toast.show(uri, '5000', 'top').subscribe(
  toast => {
    console.log(toast);
  })

  FilePath.resolveNativePath(uri).then((fileentry)=>{
 Toast.show(fileentry, '5000', 'center').subscribe(
  toast => {
    console.log(toast);
  })    //content/image.png
  File.readAsDataURL( "data",fileentry).then((file)=>{
 
blob = this.events.b64toBlob(file,512, this.events.base64MimeType(file) )
  this.events.addpdf(blob , this.navParams.get('rtextbookid') , this.textbookname, this.events.base64MimeType(file) )})
})
     })
  }

The Toasts show the URI’s and URL’s. The b64toBlob function is:

  b64toBlob(b64Data, sliceSize,fileType) {

sliceSize = sliceSize || 512;

var byteCharacters = atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
  var slice = byteCharacters.slice(offset, offset + sliceSize);

  var byteNumbers = new Array(slice.length);
  for (var i = 0; i < slice.length; i++) {
    byteNumbers[i] = slice.charCodeAt(i);
  }

  var byteArray = new Uint8Array(byteNumbers);

  byteArrays.push(byteArray);
}
let blob
blob = new Blob(byteArrays, { type: fileType });
// var url = URL.createObjectURL(blob);
return blob;

and the base64MimeType is:

  base64MimeType(encoded) {
  var result = null;

  if (typeof encoded !== 'string') {
    return result;
  }

  var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);

  if (mime && mime.length) {
    result = mime[1];
  }

  return result;
}

Any suggestions? Has anyone attempted this before?
The mimetype part doesnt work either…

Hello, I’ve tried something like that today.

What is your result with console.log ? Sometimes, if you need to retrieve and resend you need to reform data both in urlencode (normally angular does it but check), and as an array in json (json is definitely easier).

As a side note you can use Ionic Database for transition, because it has no field type yet (any number, date, string will work - it is basically a key/value online database).

Check it both, it might help,

Cant use it with console.log, Cordova_not_avaliable error prevents me from using it on my PC, so I test on my phone through ionic run android

I GOT IT WORKING!! - For future developers that face this problem. (Modified to send PDFs to firebase). Copy and paste my friends.

Make sure to get the FilePath, FileChooser and File Plugins for this.

inside my home.ts

“this.events” is my EVentData Firebase Provider, NOT THE EVENTS PLUGIN.
selectFile() {

let blob
FileChooser.open().then((uri) => {
  Toast.show(uri, '5000', 'top').subscribe(
    toast => { })
  FilePath.resolveNativePath(uri).then((fileentry) => {
    Toast.show(fileentry, '5000', 'center').subscribe(
      toast => { });
    this.makeFileIntoBlob(fileentry).then((fileblob) => {
      this.events.addtextbookfile(fileblob, this.navParams.get('rtextbookid'), this.textbookname, "application/pdf")

    })
  })
})

}

  makeFileIntoBlob(_imagePath) {
// 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: 'application/pdf' });
      imgBlob.name = 'sample.pdf';
      resolve(imgBlob);
    };

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

reader.readAsArrayBuffer(resFile);

});
});
});
}

And my firebase provider: (The name of the file and other things be changed to your liking, etc

  addtextbookfile(pdfblob, textbookid, filename,mimetype):any{
 return  this.TextbookResoursesRef.child(filename+".pdf")
          .put(pdfblob,{contentType: mimetype}).then((savedfile) => {
             this.textbookslist.child(textbookid).child("files").push({
               file: savedfile.downloadURL,
               name: filename,
               time:  Math.floor(new Date().getTime()/1000)
          });
      })
    }

Credit to: @aaronksaunders for his image example. Thanks so much man.

2 Likes