使用Javascript函数在Firestore网站中检索图像引用时遇到问题

问题描述 投票:1回答:1

我正在尝试从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函数检索数据。

[请让我来解决这个问题。

javascript html google-cloud-firestore
1个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.