Answer the question
In order to leave comments, you need to log in
How to get the url of a file uploaded to firebase?
Now I'm watching a course on integrating Vue JS with firebase, where the author displays data from firebase to the frontend. But using his code I get an error. I can't get the address of the file uploaded to the firebase repository so that I can display it in the src of the image.
The code the author uses:
import * as fb from 'firebase' // подключение библиотеки API firebase
class Ad {
constructor (title, description, ownerId, imageSrc = '', promo = false, id = null) {
this.title = title
this.description = description
this.ownerId = ownerId
this.imageSrc = imageSrc
this.promo = promo
this.id = id
}
}
export default {
state: {
ads: []
},
mutations: {
createAd (state, payload) {
state.ads.push(payload)
},
loadAds (state, payload) {
state.ads = payload
}
},
actions: {
async createAd ({commit, getters}, payload) {
commit('clearError')
commit('setLoading', true)
const image = payload.image
try {
const newAd = new Ad(
payload.title,
payload.description,
getters.user.id,
'',
payload.promo
)
const ad = await fb.database().ref('ads').push(newAd)
const imageExt = image.name.slice(image.name.lastIndexOf('.'))
const fileData = await fb.storage().ref(`ads/${ad.key}.${imageExt}`).put(image)
const imageSrc = fileData.metadata.downloadURLs[0]
await fb.database().ref('ads').child(ad.key).update({
imageSrc
})
commit('setLoading', false)
commit('createAd', {
...newAd,
id: ad.key,
imageSrc
})
} catch (error) {
commit('setError', error.message)
commit('setLoading', false)
throw error
}
},
async fetchAds ({commit}) {
commit('clearError')
commit('setLoading', true)
const resultAds = []
try {
const fbVal = await fb.database().ref('ads').once('value')
const ads = fbVal.val()
Object.keys(ads).forEach(key => {
const ad = ads[key]
resultAds.push(
new Ad(ad.title, ad.description, ad.ownerId, ad.imageSrc, ad.promo, key)
)
})
commit('loadAds', resultAds)
commit('setLoading', false)
} catch (error) {
commit('setError', error.message)
commit('setLoading', false)
throw error
}
}
},
getters: {
// ...
}
}
Answer the question
In order to leave comments, you need to log in
// const imageSrc = fileData.metadata.downloadURLs[0]
const imageSrc = await fb.storage().ref().child(fileData.ref.fullPath).getDownloadURL()
This worked for me.
Alexander, greetings!
Were you able to resolve this issue? I am also taking this course on Vue, I have a problem when creating a declaration in the application, the error is "Uncaught (in promise) TypeError: Cannot call a class as a function".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question