i wanna save my uploaded images in a folder firebase storage

i wanna save my uploaded images in a folder called "course-cover" in firebase storage
this is my code that saves uploaded images in the route of storage directly but instead of thet i wanna save them in the "course-cover" folder

 async function storeCoverCourse(coverCourse) {
  return new Promise((resolve, reject) => {
    const storage = getStorage();
    const filename = `${coverCourse.name}-${uuidv4()}`;
    const storageRef = ref(storage, filename);
    const uploadTask = uploadBytesResumable(storageRef, coverCourse);
    uploadTask.on(
      "state_changed",
      (snapshot) => {
        // Observe state change events such as progress, pause, and resume
        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
        const progress =
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log("Upload is " + progress + "% done");
        switch (snapshot.state) {
          case "paused":
            console.log("Upload is paused");
            break;
          case "running":
            console.log("Upload is running");
            break;
        }
      },
      (error) => {
        // Handle unsuccessful uploads
        reject(error);
      },
      () => {
        // Handle successful uploads on complete
        // For instance, get the download URL: https://firebasestorage.googleapis.com/...
        getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
          resolve(downloadURL);
        });
      }
    );
  });
}

const imgUrls = await Promise.all(
  [...cover].map((coverCourse) => storeCoverCourse(coverCourse))
).catch((error) => {
  toast.error("image not uploaded");
  return;
});

const formDataCopy = {
  ...formData,
  imgUrls,
  timestamp: serverTimestamp(),
};
delete formDataCopy.cover;
await addDoc(collection(db, "courses"), formDataCopy);

>Solution :

The storageRef is a StorageReference and you essentially specify path of your file with it. If your path contains /, that’ll be like a directory. Try:

const filename = `course-cover/${coverCourse.name}-${uuidv4()}`;
const storageRef = ref(storage, filename);

It’s not actually a folder under the hood but just a namespace. For more details, see How to create a folder in Firebase Storage?

Leave a Reply