如何通过index.html在firebase存储中显示图像

时间:2016-08-07 23:42:01

标签: javascript firebase firebase-storage

我已将一些图像上传到firebase的存储空间,然后我需要在网站上显示所有这些图像。我从firebase上读过doc,但仍然无法找到显示所有图片的正确方法。所以,我的问题是,我的代码在哪里显示错误的单个图像?如何同时在网络上显示所有图像(我阅读了关于堆栈溢出的帖子,它可能需要获取所有图像的URL,因此,子问题是如何获取所有图像的URL)?顺便说一下,我的firebase的数据库是空的。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

    <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
    <script>
        var config =
        {
            apiKey: "AIzaSyCKtgPuXUUqoyiwEm5sU3Blqc-A9xtBFsI",
            authDomain: "cropped-images.firebaseapp.com",
            databaseURL: "https://cropped-images.firebaseio.com",
            storageBucket: "cropped-images.appspot.com",
        };

        firebase.initializeApp(config);
        var storage = firebase.storage();
        var storageRef = storage.ref();
        var tangRef = storageRef.child('images/Tang.png');

        tangRef.getDownloadURL().then(function(url) 
        {
            var test = url
            document.querySelector('img').src = test;
        }).catch(function(error) 
        {
            switch (error.code) 
            {
                case 'storage/object_not_found':
                    break;

                case 'storage/unauthorized':
                    break;

                case 'storage/canceled':
                    break;

                case 'storage/unknown':
                    break;
            }
        });

        var test = 'firebase_url';
        document.querySelector('img').src = test;



    </script>
    <img height="125" width="125"/>
    </body>
</html>

这是我的firebase控制台的存储空间。

firebase console's storage

3 个答案:

答案 0 :(得分:12)

获取文件的下载URL需要往返Firebase服务器。这个调用(像大多数现代互联网一样)是异步发生的,因为在等待响应时阻塞浏览器将是一个糟糕的用户体验。

在代码中查看流的最简单方法是添加一些日志记录语句:

console.log('Before requesting download URL');
tangRef.getDownloadURL().then(function(url) {
    console.log('Got download URL');
});
console.log('After requesting download URL');

控制台输出将是:

  

请求下载网址

     

请求下载网址

     

获得了下载网址

可能不是您期望的顺序,这意味着设置 HTML的下载URL的代码必须位于then()回调中。

您还忽略了catch()回调中可能出现的错误。如果你在那里添加一些日志记录:

tangRef.getDownloadURL().then(function(url)                             {
  document.querySelector('img').src = url;
}).catch(function(error) {
  console.error(error);
});

代码不仅很多更短,它实际上准确地显示了问题所在:

  

获取https://firebasestorage.googleapis.com/v0/b/cropped-images.appspot.com/o/images%2FTang.png 403()

A 403表示您无权阅读图像。您很可能仍然在存储桶上具有默认安全规则,这意味着只有经过身份验证的用户才能访问这些文件。这在Firebase Storage docs for reading/writing files(强调我的)中的第一个蓝色注释中提到:

  

注意:默认情况下,Firebase存储分区需要Firebase身份验证才能上传文件。您可以change your Firebase Storage Security Rules允许未经身份验证的访问权限。由于默认的Google App Engine应用和Firebase共享此存储桶,因此配置公共访问权限也可以使新上传的App Engine文件也可公开访问。 确保在设置身份验证时再次限制对存储桶的访问。

在这种情况下,我采用了强调的方法,并在请求图像的下载URL之前添加了代码以匿名方式登录用户。这导致以下完整的代码段:

var config = {
  apiKey: "AIzaSyCKtgPuXUUqoyiwEm5sU3Blqc-A9xtBFsI",
  authDomain: "cropped-images.firebaseapp.com",
  databaseURL: "https://cropped-images.firebaseio.com",
  storageBucket: "cropped-images.appspot.com",
};

firebase.initializeApp(config);
var storage = firebase.storage();
var storageRef = storage.ref();
var tangRef = storageRef.child('images/Tang.png');

// First we sign in the user anonymously
firebase.auth().signInAnonymously().then(function() {
  // Once the sign in completed, we get the download URL of the image
  tangRef.getDownloadURL().then(function(url)                             {
    // Once we have the download URL, we set it to our img element
    document.querySelector('img').src = url;

  }).catch(function(error) {
    // If anything goes wrong while getting the download URL, log the error
    console.error(error);
  });
});

完整的工作jsbin:http://jsbin.com/kukifo/edit?html,js,console,output

答案 1 :(得分:0)

除了接受之外的其他解决方案,只需更改默认规则,以允许用户从名为images的目录中获得只读权限。

service firebase.storage {
  match /b/{bucket}/o {
    match /images/{fileName} {
      allow write: if request.auth != null;
      allow read;
    }

    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

在此之后,获取目录中文件的下载URL并删除token部分。

答案 2 :(得分:-3)

使用

<image src="your_image_url">

将图片网址提供给src属性,它将显示来自firebase存储的图片。