首页 > 解决方案 > 如何将 Firebase 存储中的图像显示到我的网站?

问题描述

<template>
  <div>
    <input type="file" id="dosya" @change="putDesign()" />
  </div>
</template>

<script>
import { initializeApp } from "firebase/app";
import { getStorage, ref, uploadBytes, listAll } from "firebase/storage";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
};

const app = initializeApp(firebaseConfig);
const storage = getStorage(app);

export default {
  data() {
    return {
      fileName: "",
      resim: "",
      photos: [],
    };
  },
  methods: {
  mounted() {
    // Create a reference under which you want to list
    const listRef = ref(storage, "design/");

    // Find all the prefixes and items.
    listAll(listRef)
      .then((res) => {
        res.prefixes.forEach((folderRef) => {
          // All the prefixes under listRef.
          // You may call listAll() recursively on them.
          console.log(folderRef);
        });
        res.items.forEach((itemRef) => {
          // All the items under listRef.
          this.photos.push(itemRef+ " ");
        });
      })
      .catch((error) => {
        // Uh-oh, an error occurred!
        console.log(error);
      });
  },
};
</script>

我可以将文件添加到我的 Firebase 存储,但我无法在我的网站上显示它们。我可以获得本地存储位置,但无法获得访问令牌,因此无法打开或显示照片。有没有办法获得访问令牌?我搜索了 Firebase 文档,但找不到任何有用的东西。

标签: javascriptfirebasevue.jsfirebase-storage

解决方案


您只需要获取downloadURL文件夹中的每个元素。它可能看起来像这样:

import { initializeApp } from "firebase/app";
import { getStorage, ref, uploadBytes, listAll, getDownloadURL } from "firebase/storage";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
};

const app = initializeApp(firebaseConfig);
const storage = getStorage(app);

export default {
  data() {
    return {
      fileName: "",
      resim: "",
      photos: [],
    };
  },
  methods: {
  mounted() {
    // Create a reference under which you want to list
    const listRef = ref(storage, "design/");

    // Find all the prefixes and items.
    listAll(listRef)
      .then((res) => {
        res.prefixes.forEach((folderRef) => {
          // All the prefixes under listRef.
          // You may call listAll() recursively on them.
          console.log(folderRef);
        });
        res.items.forEach((itemRef) => {
          // All the items under listRef.
          getDownloadURL(itemRef).then(downloadURL=>{
              this.photos.push(downloadURL);
          })
          
        });
      })
      .catch((error) => {
        // Uh-oh, an error occurred!
        console.log(error);
      });
  },
};

推荐阅读