【问题标题】:Having problem with Javascript function to retrieve image reference in Firestore web在 Firestore Web 中检索图像参考的 Javascript 函数有问题
【发布时间】:2020-05-02 20:12:48
【问题描述】:

我正在尝试从 Firestore 检索帖子,该帖子将显示在卡片中,其中包括卡片图像和卡片内容。下面的代码能够创建带有卡片内容的卡片,但没有显示image,只显示了一个图标,但没有显示图像数据。控制台中没有错误。titlesummary 已收到并显示在卡片中。

我认为我所做的不是从 Firestore 检索图像的正确方法

//Create Post
function createPost(image, title, summary) {
  let div = document.createElement('div');
  div.setAttribute('class', 'col-md-4 mb-4');

  let divCard = document.createElement('div');
  divCard.setAttribute('class', 'card');

  let divCardImg = document.createElement('div');
  divCardImg.setAttribute('class', 'view');

  let img = document.createElement('img');
  img.setAttribute('class', 'card-img-top');

  let divContent = document.createElement('div');
  divContent.setAttribute('class', 'card-body');

  let h4 = document.createElement('h4');
  h4.setAttribute('class', 'card-title');

  let p = document.createElement('p');
  p.setAttribute('class', 'card-text');

  img.src = image;
  h4.textContent = title;
  p.textContent = summary;

  divContent.appendChild(h4);
  divContent.appendChild(p);
  divCard.appendChild(divContent);
  divCardImg.appendChild(img);
  divCard.appendChild(divCardImg);
  div.appendChild(divCard);

  fashionCollection.appendChild(div);
}

// Get Posts
function getPosts() {
  db.collection("post")
    .get()
    .then(snapshot => {
      snapshot.docs.forEach(docs => {
        createPost(
          docs.data().image,
          docs.data().title,
          docs.data().summary
        );
      });
    })
    .catch(err => {
      console.log(err);
    });
}

getPosts();

createPost 函数创建具有特定属性的卡片帖子,getPost 函数检索数据。

请让一些人帮我解决这个问题。

【问题讨论】:

  • 您能否扩展“图像未显示”。有数据回来吗?如果是这样,图像变量包含什么?控制台有什么错误吗?
  • 显示一个img图标,但没有检索到图像数据,控制台没有错误,并且在卡片中显示了标题和摘要。我认为我所做的不是从 Firestore 中检索图像的正确方法。

标签: javascript html google-cloud-firestore


【解决方案1】:

答案取决于您在 Firestore 中存储图像的方式。 如果是 url,那么问题可能出在存储权限上。 如果它是 base64 编码并存储在 Bytes type 中,那么您需要在 src 属性中指出这一点,如下所示:

img.src = "data:image/png;base64," + image;

请记住,将图像存储在字节类型字段中并不好,因为它们被限制为 1 MB,首选方式是将图像托管在 Cloud Storage 中。

【讨论】:

    猜你喜欢
    • 2018-08-12
    • 2019-09-05
    • 2015-01-03
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多