Javascript Firebase getDownloadURL



我想使用Firebase Storage通过javascript在我的网页上显示几个图像。我使用:

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

问题是只显示最后一张图像。例如,如果我的文件夹中有5张图片,则所有5张图片都会正确执行带有imageIndexPathRoot的getDownload行,但仅在最后一张图片上执行img.setAttribute…行,并且该图片未显示在网页上。

// 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);
});
}
}

每次调用displayImage时,都会执行以下操作:

const img = document.getElementById('tierFoto')

因此,它将每个图像设置为相同的HTML元素,这解释了为什么您只看到最后一个图像。


如果您想在每次调用displayImage时显示一个单独的图像,则每次都需要获取(或传入(一个不同的HTML元素。如何做到这一点,取决于您的HTML结构。

例如,如果您的HTML具有带编号ID的img元素,则可以执行以下操作:

res.items.forEach(function(imageRef, i) { // 👈 get index from forEacj
displayImage(imageRef, i); // 👈 pass it to displayImage
});

然后

function displayImage(imageRef, index) { // get index from caller
const img = document.getElementById('tierFoto-'+index); // use index to look up element
...

相关内容

最新更新