Laspeed
Laspeed

Reputation: 1089

How to upload multiple images in Firebase 9 - React Js

I have an array of images that I'm trying to upload to firebase (firestore) but when I try to upload, It throws the error dataUrl.match is not a function. Here's my code:

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

The form information is uploaded but the images are not.

 The error i'm getting

Upvotes: 2

Views: 1458

Answers (1)

Laspeed
Laspeed

Reputation: 1089

It seemed like I was using the wrong function to upload the image that's why I was getting the DataUrl.match is not a function. So All I did was replace the 'uploadString' with 'uploadBytes' and that error went away. Here's the reference I followed thanks to @MousumiRoy : Error 400 Bad Request while Uploading Image to firebase storage in React Native

Here's what the code now looks like

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

Upvotes: 2

Related Questions