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

How to show images in firebase storage by index.html

我已经将一些图片上传到 firebase 的存储中,然后我需要在网站上显示所有这些图片。我已经阅读了 firebase 的文档,但仍然找不到显示所有图片的正确方法。所以,我的问题是,我的代码哪里错了,无法显示单个图像?如何同时在网络上显示所有图片(我在stack overflow上读到post,它可能需要获取所有图片的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 控制台的存储空间。

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

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

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

控制台输出将是:

Before requesting download URL

After requesting download URL

Got download 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(强调我的)的第一个蓝色注释中提到了这一点:

Note: By default, Firebase Storage buckets require Firebase Authentication to upload files. You can change your Firebase Storage Security Rules to allow unauthenticated access. Since the default Google App Engine app and Firebase share this bucket, configuring public access may make newly uploaded App Engine files publicly accessible as well. Be sure to restrict access to your Storage bucket again when you set up authentication.

在这种情况下,我采用了强调的方法并添加了代码以在请求下载图像 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

使用

<image src="your_image_url">

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

除了已接受的解决方案外,只需更改默认规则即可允许用户从名为 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 部分。