Gaurav_soni
Gaurav_soni

Reputation: 6114

Upload image to firebase and set a link in database

I know how to add data to the firebase database, I know how to upload image to the firebase storage. I am doing this in javascript.

I am not able to figure out how to link the image to my database object.

My database object is something like this

{
name:'alex',
age:23,
profession:'superhero'
image:*what to put here ???*
}

One idea is to use the object reference that is created and store the image using the same reference.

Any tutorial or ideas appreciated.

Upvotes: 3

Views: 6788

Answers (2)

lommaj
lommaj

Reputation: 773

var storageRef = firebase.storage().ref('some/storage/bucket');
var saveDataRef = firebase.database().ref('users/');
var uploadTask = storageRef.put(file);

uploadTask.on('state_changed', uploadTick, (err)=> {
  console.log('Upload error:', err);
}, ()=> {
  saveDataRef.update({
    name:'alex',
    age:23,
    profession:'superhero'
    image:uploadTask.snapshot.downloadURL
  });
});

This upload function sits inside a ES6 class and is passed a callback (uploadTick) for the .on('state_changed') from the calling component. That way you can pass back upload status and display that in the UI.

uploadTick(snap){
  console.log("update ticked", snap)
  this.setState({
    bytesTransferred:snap.bytesTransferred,
    totalBytes:snap.totalBytes
   })
}

The file to upload is passed to this upload function, but I am just using a react form upload to get the file and doing a little processing on it, your approach may vary.

Upvotes: 0

Mike McDonald
Mike McDonald

Reputation: 15953

We often recommend storing the gs://bucket/path/to/object reference, otherwise store the https://... URL.

See Zero to App and it's associated source code (here we use the https://... version) for a practical example.

Upvotes: 2

Related Questions