1
I’m making a web application with firebase, in this application I have an image registration (optional), similar to the idea of a profile (the user may or may not have a registered image if a default image is not loaded), I would like to know how to check if there is a file of that user?
Note: to "relate" the database (Realtime database) to the storage (Storage) I register the images using the user key as name, for example user registration with a key Xyz, if it registers an image, it will be in firebase.storage().ref('xyz')
If the way I use it is wrong tell me the right way to do it.
I thought first of creating a chave: valor
with the path to the image in the database, but found occupation of space unnecessary, also would have to somehow check the file name not to repeat
To show the data I call the function mostrar()
within the forEach
reading:
function ler() {
database.ref(referencia_database).once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var chave = childSnapshot.key
var obj = childSnapshot.val()
var urlImagem;
storage.ref(chave).getDownloadURL().then(function(url) {
// A imagem existe
urlImagem = url;
console.log(urlImagem);
}).catch(function(error) {
switch (error.code) {
case 'storage/object_not_found':
// A imagem não existe
urlImagem = './image/default.png';
console.log(urlImagem);
break;
default:
// Ocorreu um erro desconhecido
break;
}
});
mostrar(chave, obj.nome, urlImagem)
})
})
}
function mostrar(chave, nome, url) {
div.innerHTML += '<a href="#container">' +
'<div class="col s12 m4 l3" onclick="selecionar(\'' + chave + '\')">' +
'<div class="card">' +
'<div class="card-image">' +
'<img src="' + url + '">' +
'<span class="card-title">' + nome + '</span>' +
'</div>' +
'</div>' +
'</div>' +
'</a>'
}
Can you show the
forEach
also? Because the way you are I can’t see what values are being passed to the functionmostrar()
.– Rosário Pereira Fernandes
I put the two functions, the one that reads the data and the one that shows
– Costamilam
Very well. What happens is that the function
getDownloadURL()
is asynchronous. That means the moment you callmostrar()
, the value ofurlImagem
has not yet been defined. That’s why you should call themostrar
in thethen()
or in thecatch()
as I show in my edited reply– Rosário Pereira Fernandes