【问题标题】:How to upload multiple images in Firebase 9 - React Js如何在 Firebase 9 中上传多张图片 - React Js
【发布时间】:2022-01-20 05:05:52
【问题描述】:

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

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,
        });
      })
    );
  };
}

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

【问题讨论】:

  • 能否分享完整的错误堆栈截图?
  • 请看这个链接:ibb.co/sKffydB@Mousu​​miRoy
  • 你可以看看类似的Stackoverflow case。如果有帮助,请告诉我!

标签: reactjs google-cloud-firestore next.js firebase-storage


【解决方案1】:

似乎我使用了错误的函数来上传图像,这就是为什么我得到 DataUrl.match is not a function。所以我所做的就是用'uploadBytes'替换'uploadString',那个错误就消失了。 感谢@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,
        });
      })
    );
  };
}

【讨论】:

  • 干得好。做得好! ?
猜你喜欢
  • 2021-08-11
  • 1970-01-01
  • 2020-06-24
  • 2020-08-14
  • 2017-06-29
  • 2018-09-30
  • 2018-05-21
  • 1970-01-01
  • 2019-08-30
相关资源
最近更新 更多