使用 React 将图像上传到 Firestore

分享于2022年10月08日 firebase firebase-storage javascript reactjs 问答
【问题标题】:upload images to firestore using react使用 React 将图像上传到 Firestore
【发布时间】:2022-10-07 02:30:57
【问题描述】:

我正在尝试使用 react 将图像上传到 Firestore。我阅读了 firebase 文档,但遇到了一些问题。

这是代码:

初始化一个状态:

const [image, setImage] = useState([]);

我得到这样的图像:

 onChangeImage(e)}/>

并将其存储在这样的状态:

const onChangeImage = (e) => {
    setImage([...image, e.target.files[0]]);
    console.log(e.target.files);
  };

我正在使用 useEffect 所以当状态改变时它会记录到控制台:

useEffect(() => {
    console.log(\"picture: \", image);
  }, [image]);

这是它的记录:

lastModified: 1664394000377
lastModifiedDate: Wed Sep 28 2022 22:40:00 GMT+0300 (Eastern European Summer Time) {}
name: \"landscape.jpg\"
size: 112285
type: \"image/jpeg\"
webkitRelativePath: \"\"
[[Prototype]]: File

在 firebase 文档中,它说要为图像创建一个 ref 并为完整路径创建一个 ref,但我似乎找不到获取图像完整路径的方法。

那么有没有办法获得完整路径或任何其他方式将图像上传到firestore?


【解决方案1】:

这是上传图片的功能。你决定在哪里调用它。

// set initial state for the object 
const [data, setData] = useState(initialState);

import { getDownloadURL, uploadBytesResumable, ref } from "firebase/storage";
import { storage } from "../firebase";
const uploadFile = () => {
  //By creating a reference to a file, your app gains access to it.
  const storageRef = ref(storage);
  const uploadTask = uploadBytesResumable(storageRef, file);
  uploadTask.on(
    "state_changed",
    (snapshot) => {
      const progress =
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log("upload is" + progress + "% done");
      switch (snapshot.state) {
        case "paused":
          console.log("Upload paused");
          break;
        case "running":
          console.log("Upload running");
          break;
        default:
          break;
      }
    },
    (error) => {
      console.log(error);
    },
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((getDownloadURL) => {
        // you keep uploaded img url
        setData((prev) => ({ ...prev, img: getDownloadURL }));
      });
    }
  );
};

您上传了文件,然后在 getDownloadURL 函数中将上传的 img url 存储在一个状态中,以便您可以使用它。

为上面需要的存储做准备

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";

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

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const storage = getStorage(app);

【讨论】: