Mohamad Amjad
Mohamad Amjad

Reputation: 19

Error when trying to upload images to Firebase storage

I am trying to create an app which allow the user to upload an image and display it in the page with React and Firebase.

this is the part of the code that responsible for the issue: the image variable is coming from from the state

const [image, setImage] = useState("");
const [caption, setCaption] = useState("");
const [progress, setProgress] = useState(0)

function handleChange (e){
    if  (e.target.files[0]){
        setImage(e.target.files[0]);
    }
}
function handleUpload(){
    const uploadTask =  storage.ref('images/${image.name}').put(image)
    uploadTask.on(
        "state_changed",
        (snapshot) => {
            const progress = Math.round(
            (snapshot.bytesTransferred / snapshot.totalBytes) *  100
             );
            setProgress(progress);

           },
           (error) => {
            console.log(error);
            alert(error.message);
            },
            () => {
                storage
                .ref("images")
                .child(image.name)
                .getDownloadURL()
                .then(url => {
                    db.collection("posts").add({
                        timestamp: db.FieldValue.serverTimestamp(),
                        caption : caption,
                        imgUrl: url,
                        userName: username
                    })
                            setProgress(0);
                            setCaption("");
                            setImage(null);
                })
            }

        )
  
}

and this error get logged in the console :

Uncaught 

FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse_: null, name_: "FirebaseError"}code_: "storage/invalid-argument"message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."name_: "FirebaseError"serverResponse_: nullcode: (...)message: (...)name: (...)serverResponse: (...)__proto__: Object
    rethrowCaughtError @ react-dom.development.js:328
    runEventsInBatch @ react-dom.development.js:3336
    runExtractedPluginEventsInBatch @ react-dom.development.js:3537
    handleTopLevel @ react-dom.development.js:3581
    batchedEventUpdates$1 @ react-dom.development.js:21729
    batchedEventUpdates @ react-dom.development.js:798
    dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3591
    attemptToDispatchEvent @ react-dom.development.js:4311
    dispatchEvent @ react-dom.development.js:4232
    unstable_runWithPriority @ scheduler.development.js:659
    runWithPriority$1 @ react-dom.development.js:11077
    discreteUpdates$1 @ react-dom.development.js:21746
    discreteUpdates @ react-dom.development.js:811
    dispatchDiscreteEvent @ react-dom.development.js:4211

I have tried to change put(image) to put(blob) but it did not work

Upvotes: 0

Views: 988

Answers (1)

Emmanuel
Emmanuel

Reputation: 1494

  1. The line:
const uploadTask =  storage.ref('images/${image.name}').put(image)

Has an error, it should be using the symbol ` (backquote/backtick) instead of using single quotes ':

const uploadTask =  storage.ref(`images/${image.name}`).put(image)

otherwise you will create a reference to the literal string images/${image.name} instead of image/value_of_variable_image.jpg more about Template literals can be found here

  1. You haven't still showed us what's the content of the image variable, I can see from the code that you're calling a setState inside a function that appears to be a callback, but I'm not seeing from where are you calling, you can do it from a input like this:
<input type="file" onChange={handleChange} />

If you're already using it like that, I recommend to add console.log(image) outside of a function in order debug what's the content of the variable before sending it to put(). Just as a reference the output from the console.log(image) should be an instance of the File javascript API

Upvotes: 1

Related Questions