首页 文章

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

提问于
浏览
1

我已经将一些图像上传到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 回答

  • -3

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

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

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

    控制台输出将是:

    请求下载URL之前请求下载URL获取下载URL

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

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

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

    代码不仅短得多,而且实际上显示了问题的严重性:

    GET 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身份验证才能上载文件 . 您可以更改Firebase存储安全规则以允许未经身份验证的访问 . 由于默认的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

  • 12

    除了接受的另一个解决方案,只需更改默认规则,以允许用户从名为 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 部分 .

  • 0

    使用

    <image src="your_image_url">
    

    将图像URL提供给src属性,它将显示来自firebase存储的图像 .

相关问题