Store local image on firebase


#1

I use CameraPreview to create an image (b64). I can use

            img = 'data:image/jpeg;base64,' + imageData;
            const pictures = storage().ref('pictures/initTest');
            pictures.putString(img, 'data_url');

to succesfully upload the image to firebase.
Now I want to store the image to a certain folder:

    DATA_DIR  = this.file.externalDataDirectory;
    private writeFile(img, photo_path, photo_name) {
          const bytes: string = atob(img);
          const byteNumbers = new Array(bytes.length);
          for (let i = 0; i < bytes.length; i++) {
            byteNumbers[i] = bytes.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);

          const blob: Blob = new Blob([byteArray], { type: 'image/jpg' });

          this.file.writeFile(photo_path, photo_name, blob);
        }

This works. I find my image in the file explorer.
Now all I want is to upload this image to firebase… But no matter what I do, it does not work. I tried to convert it back to b64 - no success. I tried to upload it to firebase using:

            const pictures = storage().ref('pictures/initTest');
            pictures.put(path);

where path is exactly the path + filename where i have stored my image - no succes…
It must be sooooo simple. But how can I upload that image to firebase??? Please help, I feel so stupid as it probably is so easy…

I am quite new to Ionic and ABSOLUTELY confused…


#2

Hi,

To try to shed some light for you, Firebase Storage will need your pictures in Base64, it’s easier to set up like that.

Essentially, you want to do something like that (in my beta app, I use kind of arrays to store local pictures):

      this.imageName = 'IMG-' + new Date().getTime() + '.jpg';
      this.uploadRefStart = '/orders/' + this.uid + '/images/';
      this.uploadRefEnd = '/' + this.imageName;

      this.photosArray.push({
        photo_uploadRefStart: this.uploadRefStart,
        photo_uploadRefEnd: this.uploadRefEnd,
        photo_string: this.base64Image
      });

About how to know the path + filename of a firebase classic (js sdk) put, every firebase record returns a key, so you can chain with promises, like that:

        }).then((activeorders) => {
          console.log(activeorders.key);
          this.orderKey = activeorders.key;
          if (this.photosArray.length > 0) {
          this.doSomeThing(this.orderKey);
          }
        });

Hope it helps you,

NB: I’m using Ionic 3 and not yet ES6 TypeScript code, but you can adapt it fairly easily if you do.


#3

Thank you Francois!
However, I still don’t quite get the idea. So you use .push(…) instead of .put(…) or .putString(…)?
Let’s say I have a local folder with images (saved as b64). Should I use the .push(…) stuff or the .putString(…) stuff.
And if I use .putString(…), what is the path I have to pass?
thank you!!!