Firebase upload & get photo with ionic

i’m trying to upload an get photo in my ionic 2 app. i succeed to run the camera and save the photo in firebase but not to get and display it on my app. i’m not sure i’m doing it right, the save in firebase. i put here my code.

add-note.ts

import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { Camera } from ‘ionic-native’;

import {NotesData} from “…/…/providers/notes-data”;

/*
Generated class for the AddNote page.

See Ionic Demo: UI Components & API Customization to Create Interface for more info on
Ionic pages and navigation.
*/
@Component({
selector: ‘page-add-note’,
templateUrl: ‘add-note.html’
})
export class AddNote {
public notePicture: any;

constructor(public navCtrl: NavController,public notesData:NotesData) {}

ionViewDidLoad() {
}
addNote() {
this.notesData.addPhoto(this.notePicture);

this.navCtrl.pop();

}

takePicture(){
Camera.getPicture({
quality : 95,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.PNG,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: true
}).then(imageData => {
this.notePicture = imageData;
}, error => {
console.log("ERROR → " + JSON.stringify(error));
});
}

note-data.ts //provider for notes to upload the photo to firebase

import { Injectable } from ‘@angular/core’;
import { Http } from ‘@angular/http’;
import ‘rxjs/add/operator/map’;
import firebase from ‘firebase’
/*
Generated class for the NotesData provider.

See Angular
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class NotesData {
//user data
public currentUser: any;
public profilePictureRef: any;
//notedata
public notesList: any;

//firebase data
public photoRef:any;

constructor() {
this.currentUser = firebase.auth().currentUser.uid;
this.fireRef=firebase.database().ref();
this.photoRef=firebase.database().ref(‘users/’+this.currentUser+‘/photos’);
this.notesList =
}

addPhoto(notePicture:any){
this.photoRef.push({id:“data:image/jpeg;base64,”+notePicture});

}

}

my firebase structure photo

 updateProfilePicture(picture: any = null): any{
    return this.ProfilePictureRef.child(this.currentUser.uid)
          .putString(picture, 'base64', { contentType: 'image/png' })    
.then((savedPicture) => {
            this.userProfile.child(this.currentUser.uid).update({
              
              profilepicture: savedPicture.downloadURL});
    })
  }

This is an example of how I upload pictures to firebase. Instead of pushing "data:image etc to the Database, I push it to storage, then grab the Storage link and push it to the database as seen in the “.then” promise, the URL is stored in “downloadURL”

2 Likes

i am trying this but unable to save the picture in storage


            this.profileData.updateProfilePicture(this.imageSrc);
// sending photo from my page to provider 


    this.ProfilePictureRef=firebase.storage().ref('/userProfile/');
//..setting storage reference

updateProfilePicture(picture: any = null): any{
    return this.ProfilePictureRef.child(this.currentUser.uid)
          .putString(picture, 'base64', { contentType: 'image/png' })    
.then((savedPicture) => {
            this.userProfile.child(this.currentUser.uid).update({
              
              profilepicture: savedPicture.downloadURL});
    })
  }

it was invalid string of base64 . i removed that

use “.put” instead of “.putString”, see what happens.

If it takes a long time for the picture to reach the database I think blobs should work…

thanks . its working now
i used split function and supplied picture variable string.
:slight_smile:

1 Like

Splendid!

hey @trevaun23 your example did wonders. How would i pull the picture from storage to show in my profile tags

save the url of image in db and then retrieve it

getUserProfile(): any {
     this.uid = this.currentUser.uid;
    return this.userProfile.child(this.currentUser.uid);
    }

Thats to get it from firebase. “profile-data.ts”

 this.profiledata.getUserProfile().on('value', snap => {
      this.profile = snap.val();
     this.profilepicture = this.profile.profilepicture;
    })

This is to grab it using the provider in “home.ts”

<ion-avatar *ngIf="profilepicture" item-right (click)="goToProfile()">
      <img [src]="profilepicture">
    </ion-avatar>

This is to show it in html “home.html”

@Darksideous

I’m trying the same code:
In my constructor:
this.fireAuth = firebase.auth(); // We are creating an auth reference.
this.userProfile = firebase.database().ref(’/userProfile’);
this.profilePictureRef = firebase.storage().ref(’/userProfilePhoto/’);

uploadProfilePhoto(profilePicture: any){

var user = this.fireAuth.currentUser;

alert(profilePicture);
alert(user.uid);

this.profilePictureRef.child(user.uid).putString(profilePicture, ‘base64’, { contentType: ‘image/png’ }).then((savedPicture) => {
alert(savedPicture.downloadURL);
this.userProfile.child(user.uid).update({
profilepicture: savedPicture.downloadURL});
})

}

but this doesn’t work. The image does not get uploaded to the corresponding firebase storage nor reaches the database. Could you please share your thoughts?

if you are getting any error .check that and post it.
i was getting invalid string error .
so done this.

[code]

let pic:Array;
pic=Array(2);
pic=picture.split(’,’);
// i used it to seperate invalid string with picture string
let msg:string;
msg=pic[1];
[/code]'
use that msg variable to pass in firebase

@ This might negate the need to push to database at all. Thought i would share

<input type="button" value ="view Image" id="viewbtn" onclick="showimage();">
<img src="test" height="125px" width="200px"/>
1 Like

whoa… this does make sense… well, in certain cases… I’ll definitely try this though.

My pictures that are pushed have random names. So those would need to have some property stored somewhere to get it back

1 Like

Most definitely let me know what you think when you try it out. :slight_smile:

1 Like

I modified some tutorials online so that it didnt require a user auth, here’s a repo https://github.com/Matt4759/Ionic3-FirebaseImageSharing.
Just plug your firebase creds into app.component, this puts it in storage under the title they input, and then displays that on the home page.

1 Like

please how can i use url to retrieve the images

In Ionic 4 you can try using Firestore. Check tutorial link here