uploading and downloading storage images in firebase with VueJs

Tags: , , , ,



im building this simple application using Vue/vuex and firebase where i want to facilitate users upload images and once the app gets updated those images get reached from firebase storage , modifying the current database with the new uploaded image Here is my code:

createMeet({ commit, getters }, payload) {
      const newMeet = {
        title: payload.title,
        description: payload.description,
        location: payload.location,
        date: payload.date,
        video_url: payload.video_url,
        idCreator: getters.getUser.id
      }
      let image_url;
      let key;
      firebase.database().ref('meetUps').push(newMeet)
        .then((data) => {
          console.log(data)
          key = data.key
          return key
        })
        .then(key => {
          const filename = payload.image.name
          const fileExtension = filename.slice(filename.lastIndexOf('.'))
          return firebase.storage().ref('meetUps/' + key + '.' + fileExtension).put(payload.image)
        })---the image get storaged in the firebase storage

        .then(fileData => {
          image_url = fileData.metadata.downloadURLs()
          return firebase.database().ref('meetUps/').child(key).update({ image_url: image_url })
        })--------->updating in the database the storaged object in there passing a new paranmeter
                    image_url, with a new value contained in variable iimage_url
        .then(() => {
          commit('meetsCreator', {
            ...newMeet,
            image_url: image_url,------------>putting changes in some mutation which modifies the state
            id: key,

          })
        })
        .catch(error => {
          console.log(error)
        })
      // commit('meetsCreator',newMeet)
    },

the images get push to the firebase storaged but once i try to modify the database adding this new element (image) using downloadUrls, doesnt work. Any advice please?….thanks in advance!!!

Answer

You need to use the getDownloadURL() method from the JavaScript SDK, which is asynchronous and returns a Promise that resolves with the download URL.

So, the following should do the trick:

  //...
  firebase.database().ref('meetUps').push(newMeet)
    .then(ref => {
      key = ref.key
      const filename = payload.image.name
      const fileExtension = filename.slice(filename.lastIndexOf('.'))
      return firebase.storage().ref('meetUps/' + key + '.' + fileExtension).put(payload.image)
    })
    .then(uploadTaskSnapshot => {
       return uploadTaskSnapshot.ref.getDownloadURL();
    .then(url => {
      return firebase.database().ref('meetUps/').child(key).update({ image_url: url })
    })
    //....


Source: stackoverflow