How to check if file exists in Firebase web Storage?

Asked

Viewed 505 times

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 function mostrar().

  • I put the two functions, the one that reads the data and the one that shows

  • Very well. What happens is that the function getDownloadURL() is asynchronous. That means the moment you call mostrar(), the value of urlImagem has not yet been defined. That’s why you should call the mostrar in the then() or in the catch() as I show in my edited reply

1 answer

2


You can try to get the image download URL. If the error object_not_found is because she doesn’t exist.

var ref = firebase.storage().ref('xyz');
var urlImagem;
ref.getDownloadURL().then(function(url) {
  // A imagem existe
  urlImagem = url;
  console.log(urlImagem);
  mostrar(chave, obj.nome, urlImagem)
}).catch(function(error) {
  switch (error.code) {
    case 'storage/object_not_found':
      // A imagem não existe
      urlImagem = './image/default.png';
      console.log(urlImagem);
      mostrar(chave, obj.nome, urlImagem)
      break;

    default:
      // Ocorreu um erro desconhecido
      break;
  }
});
  • It didn’t work on the question is how I did in the code

  • You do not need to form the URL manually, the function getDownloadURL() returns the image URL (I edited my response to show this). Try the updated response. Have you tested both cases? When does the image exist and when it doesn’t exist? Neither of the 2 showed anything on the console?

  • Yes I tested both, one gives the 404 error in the console and the other appears the firebase url. And the tag appears <img src(unknown)>. I tested it the other way you did but it didn’t work either

  • I forgot to change the variable names, the console shows the same thing but the tag is now <img src="undefined">

  • You can show the code you are using to put the url in the img tag?

  • added to the question

  • I understood, I thought it would be something like this, the url has been sent empty before being checked and set the correct value. It worked with the image but when there is no image the default.png is not sent (only a div appears in the display function is not called I think)

  • I took the switch case, so the default image will be loaded in any case of error and it worked I think was entering another error code. But one more question if you can help me, getDownloadURL() does the image loading? If yes this does not cause a performance drop, since the same image would be loaded twice?

  • Yes, the getDownloadURL() does image loading. But how so 2 times? You are calling getDownloadURL() more than once?

  • No, but when I made the innerHTML of the image (<img>), html will not load this image again?

  • When I said "uploading" I meant the process of reading the Firebase image. (I think you’re talking about uploading the image to the page). So no, the getDownloadURL won’t load the image to the page, that’s the innerHTML who does and does once.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.