Home > database >  Javascript Firebase getDownloadURL
Javascript Firebase getDownloadURL

Time:11-29

I want to display several images on my webpage via javascript using Firebase Storage. I use:

getDownloadURL(ref(storage, imageIndexPathRoot)).then((url) =>{
img.setAttribute('src', url);

The problem is that only the last image is displayed. If I have e.g. 5 pictures in my folder, the getDownload line with the imageIndexPathRoot is correct executed for all 5 images, but only at the last image the line img.setAttribute... is executed and unly this image was displayed on the webpage.

    // Now we get the references of these images
   listAll(listRef).then((res) => {
     res.items.forEach(function(imageRef) {
      // And finally display them
      console.log(imageRef);
      displayImage(imageRef);
     });
    }).catch((error) => {
    // Handle any errors
    console.log("Error 1");
    });

  function displayImage(imageRef) {
    const img = document.getElementById('tierFoto');
    img.src = imageRef.fullPath;
    getDownloadURL(ref(storage, imageIndexPathRoot)).then((url) =>{
    img.setAttribute('src', url);
    })
    .catch((error) => {
      console.log(error);
    });
  }
}

CodePudding user response:

Every time displayImage is called, it does:

const img = document.getElementById('tierFoto')

So it sets each image to the same HTML element, which explains why you only see the last of the images.


If you want to show a separate image each time you call displayImage, you'll need to get (or pass in) a different HTML element each time. How to do that, depends on your HTML structure.

For example, if your HTML has img elements with numbered IDs, you could do:

res.items.forEach(function(imageRef, i) { //            
  • Related