如何在 Firebase 9 中上传多张图片 - React Js

How to upload multiple images in Firebase 9 - React Js

我有一组图像正在尝试上传到 firebase (firestore),但是当我尝试上传时,它抛出错误 dataUrl.match 不是函数。这是我的代码:

Form.js

import { db, storage } from "../../firebase";
import {
  addDoc,
  collection,
  doc,
  serverTimestamp,
  updateDoc,
} from "@firebase/firestore";
import { getDownloadURL, ref, uploadString } from "@firebase/storage";
import { useSelector } from "react-redux";

function Form() {
  const Images = useSelector((state) => state.draggedImages.images);

  const imageTarget = Images.length - 1;

  const SendPost = async () => {
    const docRef = await addDoc(collection(db, "Post-Ad"), {
      id: session.user.uid,
      username: session.user.name,
      ProductName: name,
      AdTitle: title,
      AdDescription: description,

      timestamp: serverTimestamp(),
    }).then(() => console.log("sent to firestore"));

    const imageRef = ref(storage, `Post-Ad/${docRef?.id}/image`);
    Images[imageTarget]?.map((Img) =>
      uploadString(imageRef, Img, "data_url").then(async () => {
        const downloadURL = await getDownloadURL(imageRef);
        await updateDoc(doc(db, "posts", docRef.id), {
          image: downloadURL,
        });
      })
    );
  };
}

表单信息已上传,但图片未上传。

似乎我使用了错误的函数来上传图片,这就是为什么我得到 DataUrl.match 不是函数的原因。所以我所做的就是将 'uploadString' 替换为 'uploadBytes' 并且错误消失了。 感谢@Mousu​​miRoy,这是我遵循的参考:Error 400 Bad Request while Uploading Image to firebase storage in React Native

下面是代码现在的样子

Form.js

import { db, storage } from "../../firebase";
import {
  addDoc,
  collection,
  doc,
  serverTimestamp,
  updateDoc,
} from "@firebase/firestore";
import { getDownloadURL, ref, uploadBytes } from "@firebase/storage";
import { useSelector } from "react-redux";

function Form() {
  const Images = useSelector((state) => state.draggedImages.images);

  const imageTarget = Images.length - 1;

  const SendPost = async () => {
    const docRef = await addDoc(collection(db, "Post-Ad"), {
      id: session.user.uid,
      username: session.user.name,
      ProductName: name,
      AdTitle: title,
      AdDescription: description,

      timestamp: serverTimestamp(),
    }).then(() => console.log("sent to firestore"));

    const imageRef = ref(storage, `Post-Ad/${docRef?.id}/image`);
    Images[imageTarget]?.map((Img) =>
      uploadBytes (imageRef, Img, "data_url").then(async () => {
        const downloadURL = await getDownloadURL(imageRef);
        await updateDoc(doc(db, "posts", docRef.id), {
          image: downloadURL,
        });
      })
    );
  };
}