Firebase Storage - Upload image to firebase storage and create a link to that in realtime database

24,749

Solution 1

to link to the database try this:

var ref= firebase.database().ref("Uploads");
var storage = firebase.storage();
var pathReference = storage.ref('images/stars.jpg');
pathReference.getDownloadURL().then(function(url) {
ref.push().set({
imgurl: url
});

more info here:

https://firebase.google.com/docs/storage/web/download-files

https://firebase.google.com/docs/storage/web/upload-files

after adding it to the storage, you will be able to get the url using getDownloadUrl() and then add it in the db:

Uploads
  pushid
     imgurl: url

Solution 2

Check example application using Firestore(Storage) to save image file and using Cloud Storage(Database) to save image path, name, and file size.

enter image description here

Upload Image

// The main task
this.task = this.storage.upload(path, file, { customMetadata });

Save Image Info

  addImagetoDB(image: MyData) {
    //Create an ID for document
    const id = this.database.createId();

    //Set document id with value in database
    this.imageCollection.doc(id).set(image).then(resp => {
      console.log(resp);
    }).catch(error => {
     console.log("error " + error);
    });
  }

Source tutorial Link

Share:
24,749
Benjamin Sommer
Author by

Benjamin Sommer

Updated on July 09, 2022

Comments

  • Benjamin Sommer
    Benjamin Sommer almost 2 years

    I am having trouble uploading an image to firebase storage. I need to have an input object in the HTML with a type of file. Then I need the image selected for that input to be uploaded to the firebase storage for my project. Is there also a way to store the location of that image in the real-time database so it can be accessed later? How would I do this?

    Thank you in advance

    • Benjamin Sommer
      Benjamin Sommer over 6 years
      Yes but I'm mainly looking for info on how to upload images easily
    • Peter Haddad
      Peter Haddad over 6 years
      well this: firebase.google.com/docs/storage/web/upload-files is the only way. After that you can implement my answer below
    • Asad Ali Choudhry
      Asad Ali Choudhry over 4 years
      Have a look at this utility class to upload images, videos, and files to Firebase Storage. handyopinion.com/…
  • Thomas David Kehoe
    Thomas David Kehoe over 5 years
    I think you meant put(), not push().
  • Peter Haddad
    Peter Haddad over 5 years
    No push() to create a randomid and then set the image under it