簡體   English   中英

如何通過index.html在Firebase存儲中顯示圖像

[英]How to show images in firebase storage by index.html

我已將一些圖像上傳到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;
        }).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控制台的存儲

要獲取文件的下載URL,需要往返Firebase服務器。 該調用(與大多數現代Internet一樣)是異步發生的,因為在等待響應時阻止瀏覽器會帶來糟糕的用戶體驗。

在代碼中查看流程的最簡單方法是添加一些日志記錄語句:

console.log('Before requesting download URL');
tangRef.getDownloadURL().then(function(url) {
    console.log('Got download URL');
});
console.log('After requesting 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()

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

// 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,控制台,輸出

除了已接受的解決方案外,只需更改默認規則即可允許用戶從名為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部分。

采用

<image src="your_image_url">

將圖片網址提供給src屬性,它將顯示Firebase存儲中的圖片。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM