首页 > 解决方案 > 如何使用 reactjs 将图像上传到 Firebase web v9

问题描述

我在将图像上传到 firebase 但使用网络版本 9 时遇到问题。我正在关注他正在构建 facebook 克隆的其中一个平台上的教程。我被困在firebase上传图像和文件的这一部分......我检查了firebase的文档,我试图弄清楚应该改变,但我做不到。我想要的是将firebase代码从旧版本转换为最新的web V9。这是我的代码,但在以前的版本中:

import { useSession } from 'next-auth/client';
import { useRef, useState } from 'react';
import { db, storage } from '../firebase';
import firebase from 'firebase';

function InputBox() {
    const [session] = useSession();
    const inputRef = useRef(null);
    const filepickerRef = useRef(null);
    const[imageToPost, setImageToPost] = useState(null);

    const sendPost = (e) => {
        e.preventDefault();

        if (!inputRef.current.value) return;

        db.collection('posts').add({
            message: inputRef.current.value,
            name: session.user.name,
            email: session.user.email,
            image: session.user.image,
            timestamp: firebase.firestore.FieldValue.serverTimestamp()
        }).then(doc => {
            if (imageToPost) {
                const uploadTask = storage.ref(`posts/${doc.id}`).putString(imageToPost, 'data_url')

                removeImage();

                uploadTask.on('state_change', null, error => console.error(error), 
                () => {
                    //When the upload completes
                    storage.ref(`posts`).child(doc.id).getDownloadURL().then(url => {
                        db.collection('posts').doc(doc.id).set({
                            postImage: url
                        },
                        { merge: true}
                        );
                    });
                });
            }
        });

        inputRef.current.value = "";
    };

    const addImageToPost = (e) => {
        const reader = new FileReader();
        if (e.target.files[0]) {
            reader.readAsDataURL(e.target.files[0]);
        }
        reader.onload = (readerEvent) => {
            setImageToPost(readerEvent.target.result);
        };
    };

    const removeImage = () => {
        setImageToPost(null);
    };

    return (here is my jsx)

标签: reactjsfirebasefirebase-storage

解决方案


如果您的 firebaseConfig 没问题,那么这应该可以!

import { setDoc, doc } from "firebase/firestore";
import { ref, uploadString, getDownloadURL, getStorage  } from "firebase/storage";

            if (imageToPost) {
                const storage = getStorage();
                const storageRef = ref(storage, `posts/${docum.id}`);
                const uploadTask = uploadString(storageRef, imageToPost, 'data_url');

                uploadTask.on('state_changed', null,
                (error) => {
                  alert(error);
                },
                () => {
                  getDownloadURL(uploadTask.snapshot.ref)
                  .then((URL) => {
                     setDoc(doc(db, "posts", docum.id), { postImage:URL }, { merge: true});
                  });
                }
              )
              removeImage();
            };

推荐阅读