如何通过index.html在firebase存储中显示图片 [英] How to show images in firebase storage by index.html

查看:251
本文介绍了如何通过index.html在firebase存储中显示图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上传了一些图片到firebase的存储,然后我需要在网站上显示所有这些图片。我已经阅读了firebase的文档,但仍然找不到显示所有图片的正确方法。所以,我的问题是,我的代码错在哪里显示一个单一的图像?如何同时显示网络上的所有图像(我读过堆栈溢出的帖子,可能需要获取所有图像的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;
{
case'storage / object_not_found':
break; $(


'存储/未授权':
中断;

'存储/取消'情况:
中断;

存储/未知:
break;
}
});

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



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

以及我的firebase控制台的存储空间。


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



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

$ $ $ $ $ $ $ codeonsole.log('请求下载URL之前');
tangRef.getDownloadURL()。then(function(url){
console.log('Got download URL');
});
console.log('请求下载URL后');

控制台输出将是:


在请求下载URL之前



在请求下载URL之后



p>

可能不是您所期望的顺序,这意味着将下载URL设置为HTML的代码,必须在中,然后()回调。



你也忽略了可能在 catch()回调。如果你添加一些日志记录:

pre $ t $ c $ t> tangRef.getDownloadURL()。然后(函数(url){
文档。 catch(function(error){
console.error(error);
});

这段代码不仅缩短了很多,而且实际上显示了什么问题是:


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




<403>表示您没有权限读取图像。您很可能仍然在您的存储桶中具有默认安全规则,这意味着只有通过身份验证的用户才能访问这些文件。这在 Firebase存储文档中用于读取/写入文件的第一个蓝色备注中提到<注::默认情况下,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');
$ b $ //首先我们匿名登录
firebase.auth()。signInAnonymously()。然后(function(){
//一旦签名完成,我们获取图片
的下载URL tangRef.getDownloadURL()。然后(函数(url){
//一旦我们有了下载URL,我们将它设置为我们的img元素
文档。 catch(function(error){
//如果在获取下载URL时发生任何错误,记录错误
console.error(error);
});
});

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


I have uploaded some images to firebase's storage, and then I need to show all of these images on a website. I have read the doc from firebase, but still can't find the right way to show all pictures. So, my questions are, where is my code wrong to show an even single image? How to show all images on the web at the same time (I read a post on stack overflow, it may need to get all images' URLs, so, the sub question is how to get all images' URLs)? By the way, my firebase's database is empty.

<!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>

And this my firebase console's storage.

解决方案

Getting the download URL for a file requires a roundtrip to the Firebase servers. This call (like most of the modern internet) happens asynchronously, since blocking the browser while waiting for a response would be a bad user experience.

The easiest way to see the flow in your code is to add some logging statements:

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

The console output will be:

Before requesting download URL

After requesting download URL

Got download URL

Probably not the order you expected and it means the code to set the download URL to the HTML, must be inside the then() callback.

You're also ignoring the errors that might be raised in the catch() callback. If you add some logging there:

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

The code is not only a lot shorter, it actually shows precisely what the problem is:

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

A 403 means that you don't have permission to read the image. Most likely you still have the default security rules on your Storage bucket, which means that only authenticated users can access the files. This is mentioned in the first blue note in the Firebase Storage docs for reading/writing files (emphasis mine):

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.

In this case, I went with the emphasized approach and added code to sign in the user (anonymously) before requesting the download URL of the image. This leads to the following complete code snippet:

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);
  });
});

The complete working jsbin: http://jsbin.com/kukifo/edit?html,js,console,output

这篇关于如何通过index.html在firebase存储中显示图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆