MASTER KOURANI
MASTER KOURANI

Reputation: 41

upload images to firestore using react

Im trying to upload an image to Firestore using react. I read the firebase documentation but I had some problems.

here is the code:

initialize a state :

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

I'm getting the image like this :

<input type="file" id="image" accept="image/*"className="hidden" onChange={(e) => onChangeImage(e)}/>

and storing it in a state like this :

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

and I'm using useEffect so when the state changes it logs to the console:

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

here is what it's logging:

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

in the firebase documentation, it says to create a ref for the image and a ref for the full path and I can't seem to find a way to get the full path of the image.

so is there a way I can get the full path or any other way to upload an image into firestore?

Upvotes: 0

Views: 1883

Answers (1)

Yilmaz
Yilmaz

Reputation: 49681

Here is the function to upload image. you decide where to call it.

// set initial state for the object 
const [data, setData] = useState(initialState);
// call setfile on file input onChange
const [file, setFile] = useState(null);


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,file.name);
  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((downloadedURL) => {
        // you keep uploaded img url
        setData((prev) => ({ ...prev, img: downloadedURL }));
      });
    }
  );
};

you uploaded file and then in getDownloadURL function you store the uploaded img url in a state, so you can use it.

prepare for the storage that you need above

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

Upvotes: 2

Related Questions