0

I am having issue to upload an SVG image to firebase storage. The upload seems to work correctly how when I am trying to click on the link. It returns the error file empty as per screenshot below.

error message

firebase interface

Please see below my upload function

import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"

export const uploadToFirebase = async (file) => {
    const storage = getStorage()
    const storageRef = ref(storage, "images/avatar.svg")
    const metadata = {
        contentType: "image/svg+xml",
    }
    const uploadTask = uploadBytesResumable(storageRef, file, metadata)
    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 is paused")
                    break
                case "running":
                    console.log("Upload is running")
                    break
            }
        },
        (error) => {
            // A full list of error codes is available at
            // https://firebase.google.com/docs/storage/web/handle-errors
            switch (error.code) {
                case "storage/unauthorized":
                    // User doesn't have permission to access the object
                    break
                case "storage/canceled":
                    // User canceled the upload
                    break

                // ...

                case "storage/unknown":
                    // Unknown error occurred, inspect error.serverResponse
                    break
            }
        },
        () => {
            // Upload completed successfully, now we can get the download URL
            getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
                console.log("File available at", downloadURL)
            })
        }
    )
}

i am calling this function in my home component as fellow

 useEffect(() => {
        uploadToFirebase("../public/avatar.svg")
    }, [])

Can someone help me underytand what is wrong with my code,please?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Leo
  • 481
  • 2
  • 9
  • 20

1 Answers1

0

You pass a String to your uploadToFirebase() method which results in calling the uploadBytesResumable() method with a String as second argument.

As explained in the doc (above link), this second argument shall be a Blob, a Uint8Array or an ArrayBuffer.


Following our below comments: I'm not verse in reactjs but you need to get the image from your public folder as a Blob Object (or as a File Object, which is "a specific kind of Blob") and pass it to your uploadToFirebase() method. The following SO question & answers give several ways to do that (untested).

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121