【问题标题】:Javascript Firebase getDownloadURLJavascript Firebase getDownloadURL
【发布时间】:2022-01-04 17:25:47
【问题描述】:

我想使用 Firebase 存储通过 javascript 在我的网页上显示几张图片。 我用:

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

问题是只显示最后一张图片。如果我有例如我的文件夹中有 5 张图片,带有 imageIndexPathRoot 的 getDownload 行对所有 5 张图片都正确执行,但仅在最后一张图片上执行 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);
    });
  }
}

【问题讨论】:

    标签: javascript html firebase url firebase-storage


    【解决方案1】:

    每次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
      ...
    

    【讨论】:

    • 您好弗兰克,非常感谢您的回答,我尝试了您的建议,但还是有问题。
    • “我还是有问题” 这很难解决。当您使用我的答案中的代码时发生了什么变化?您还有哪些具体问题需要进一步帮助?
    • 第一个代码段似乎工作正常,问题出在 displayImage 函数中(在 getDownloadURL 处)。使用正确的参数 imageRef 正确调用该函数。在调试时,我看到第一个,第二个...图像 img.setAttribute('src', url) 没有执行,并且 url 也未定义。在一些图像之后(不是最后一个)我得到一个“错误 1”,执行了 img.setAttribute('src', url) 并且还定义了 url (https://...) 并显示了这张图片.
    • 也许我的问题是几个“进程”并行运行?
    • 原始代码中的问题是您将所有图像设置为单个 HTML 元素。要查看所有图像,您需要将每个图像设置为自己的 HTML 元素,该元素要么已经存在(这是我的答案中的代码所假定的),要么是您从代码本身生成的。
    猜你喜欢
    • 2021-04-06
    • 2020-05-13
    • 2021-02-15
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2017-10-18
    • 2018-01-04
    相关资源
    最近更新 更多