如何在React中显示firebase存储中的所有图像?

eblbsuwk  于 2023-02-25  发布在  React
关注(0)|答案(3)|浏览(135)

我尝试在我的React应用程序中显示Firebase存储中的图像。我可以使用listall从Firebase存储中获取所有图像。但我不知道如何在用户界面上显示这些图像。我尝试使用map方法,但不起作用。此外,即使页面重新加载,我也希望保持这些显示。我应该使用localstrage还是useEffect?
请帮帮我,这是我的密码。

const PhotoButton = () => {

    var storageRef = firebase.storage().ref("images");
  
    const [image, setImage] = useState("");
    const [imageUrl, setImageUrl] = useState([]);
    const handleImage = event => {
        const image = event.target.files[0];
        setImage(image);
    };

    const onSubmit = event => {
        event.preventDefault();
        if (image === "") {
          console.log(“error);
          return;
        }
      
        const uploadTask = storage.ref(`/images/${image.name}`).put(image);
        uploadTask.on(
          firebase.storage.TaskEvent.STATE_CHANGED,
          next,
          error,
          complete
        );
    };

    const complete = () => {
        storage
          .ref("images")
          .child(image.name)
          .getDownloadURL()
          .then(fireBaseUrl => {
            setImageUrl(fireBaseUrl);
          });
    };

    // Now we get the references of these images
    storageRef.listAll().then(function(result) {
        result.items.forEach(function(imageRef) {
        // And finally display them
        console.log(result.items);
        displayImage(imageRef);
        });
    }).catch(function(error) {
        alert(“error!”)
    });
  
    function displayImage(imageRef) {
        imageRef.getDownloadURL().then(function(url) {
            setImageUrl.push(url);
        // TODO: Display the image on the UI
        }).catch(function(error) {
        // Handle any errors
        });
    }
   
    return(
        <div>
            <h3 className={classes.addPhotoText}>Photos</h3>
            <div className="addphoto">
            <form onSubmit={onSubmit}>
                <input type="file" onChange={handleImage} />
                <Button type="submit" className={classes.PhotoButton}>Submit</Button>
            </form>
            </div>
            <img src={imageUrl} />

            {imageUrl.map((url) => (
                <img src={url}/>
            ))}
        </div>
    );

}

export default PhotoButton
mwngjboj

mwngjboj1#

它用这个代码工作。

useEffect(() => {
    const fetchImages = async () => {

    let result = await storageRef.child('images').listAll();
        let urlPromises = result.items.map(imageRef => imageRef.getDownloadURL());
    
        return Promise.all(urlPromises);

    }
    
    const loadImages = async () => {
        const urls = await fetchImages();
        setFiles(urls);
    }
    loadImages();
    }, []);
hof1towb

hof1towb2#

对我来说,我需要添加一些东西到@via回答,让它工作。我箍它可以帮助别人
Firebase配置

import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/storage";
import "firebase/auth";

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

if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig);
}

const auth = firebase.auth();
const db = firebase.firestore();
const storage = firebase.storage();

export { db, storage, auth };

代码

import { storage } from "../components/config/config";

 // Get all the images from Storage
    const [files, setFiles] = useState();

useEffect(() => {
    const fetchImages = async () => {
      let result = await storage.ref().child("Name Of Your Files Map in storage").listAll();
      let urlPromises = result.items.map((imageRef) =>
        imageRef.getDownloadURL()
      );

      return Promise.all(urlPromises);
    };

    const loadImages = async () => {
      const urls = await fetchImages();
      setFiles(urls);
    };
    loadImages();
}, []);

  console.log(files);
fafcakar

fafcakar3#

使用firebase web-version 9,这对我列出firebase存储中的所有图像很有效。
Firebase配置

import { initializeApp } from "firebase/app"
import { getStorage } from "firebase/storage"

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

};

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

export { app, storage };

代码

import { storage } from '../firebase';
import { ref, list, listAll, getDownloadURL } from "firebase/storage"

  fetchImages = async () => {
    const storageRef = ref(storage, 'images/');
    const result = await listAll(storageRef);
  
    const urlPromises = result.items.map((imageRef) => getDownloadURL(imageRef));
  
    return Promise.all(urlPromises);
};

文档链接:www.example.comhttps://firebase.google.com/docs/storage/web/list-files#web-version-9

相关问题