【问题标题】:Firebase getDownloadURL From Storage Unable To Set Img Src来自存储的 Firebase getDownloadURL 无法设置 Img Src
【发布时间】:2016-12-26 04:40:49
【问题描述】:

我正在尝试复制这个问题here 的结果。我可以在有效的数据库子节点上调用getDownloadURL(),但它返回的结果似乎无法设置为IMG 的src。 这是我目前用来尝试获取下载 URL 的代码:

var storage = firebase.storage();
var storageRef = storage.ref();
var imgRef = storageRef.child('profile-pictures/1.jpg');
var pulledProfileImage = imgRef.getDownloadURL();

然后我通过这样做将pulledProfileImage 推入一个数组:

dataArray.push(pulledProfileImage)

将数组(连同其他信息)发送到用数据填充表的函数。此处使用此代码引用图像本身:

cell1.innerHTML = '<img id="profileImage" src="'+dataArray[0]+'">';

当我在代码执行后检查源代码时,src 设置为[Object, Object]。我也有脚本记录结果,当它这样做时,看起来像这样:

0:C
Hc:false
N:2
Pa:null
Wb:false
ja:null
na:"https://firebasestorage.googleapis.com/v0/b/app-name-da7a1.appspot.com/..."
s:null

奇怪的是,如果我让控制台打印出一个不同的属性,比如上面列表中的Wb,通过调用console.log(Array[0].Wb)它会打印出false PERFECTLY....每个布尔值似乎都很好,只是不是字符串或数字。

作为参考,我的存储结构如下所示:

----root
  |
  |------profile-pictures
             |---------------------- img1.png <--the console is trying to print this one
             |
             |---------------------- img2.png 

我的数据库结构来查找要提取的图像的名称是这样的:

----root
  |
  |----folder1
          |
          |
          |----subfolder1
                   |
                   |
                   |----subfolder2
                           |
                           |
                           |--------img1.png
                           |
                           |--------img2.png

基本上,我的代码导航到子文件夹 2,拉取子值,然后进入存储并尝试从那里拉取它们。

【问题讨论】:

  • 请分享minimal, complete code that reproduces the problem。您现在分享的 sn-ps 留下了太多的想象空间。该代码可能还取决于您的数据库的 JSON 结构,因此也包括一个具有代表性的 sn-p(作为文本,没有屏幕截图)。
  • 弗兰克,感谢您的回复。我改变了这个问题——现在的邮件问题是只有boolean 值可以在引用时打印,但numbersstrings 不能。谢谢!
  • 你还没有分享minimal complete code that reproduces the problem。如果您在问题中包含这样的MCVE,您更有可能获得帮助。
  • 弗兰克,你能检查一下编辑后的问题吗?谢谢!

标签: javascript firebase firebase-storage


【解决方案1】:

这里的技巧是getDownloadURL 是一个异步函数,它恰好返回一个承诺(根据the docs):

var storage = firebase.storage();
var storageRef = storage.ref();
var imgRef = storageRef.child('profile-pictures/1.jpg');
// call .then() on the promise returned to get the value
imgRef.getDownloadURL().then(function(url) {
  var pulledProfileImage = url;
  dataArray.push(pulledProfileImage);
});

这将在本地工作,但该 URL 列表不会在所有浏览器之间同步。相反,您想要的是使用数据库来同步 URL,就像我们在 Zero To App 中所做的那样 (video, code)。

【讨论】:

  • 这个脚本在 PHP 中可用吗?我想在php中使用。
  • PHP 是一种在您自己的服务器上运行的后端语言,而我们展示的是直接在客户端上运行的 JavaScript。它们是两个完全不同的东西,所以不能直接比较。
猜你喜欢
  • 2018-11-12
  • 2021-04-06
  • 2016-12-05
  • 1970-01-01
  • 2020-04-02
  • 2018-10-02
相关资源
最近更新 更多