Chryzz
Chryzz

Reputation: 25

React JS and Firebase : Cannot upload image

Im trying to create a signup form for my website. Im storing the user information on MongoDB and their images on Firebase. When Signup button is pressed i get "POST https://firebasestorage.googleapis.com/v0/b/app/o?name=image.jpg 403" in the browser's console

I have seen several tutorials on how to upload files to firebase storage using React.js and this is what i tried:

const [file , setfile] = useState(null);

const handleClick = (e)=>{
    e.preventDefault();
    const fileName = new Date().getTime() + file?.name;
    const storage = getStorage(app);
    const StorageRef = ref(storage , fileName);
    
    const uploadTask = uploadBytesResumable(StorageRef, file);
    uploadTask.on('state_changed', 

  () =>  {
    // Handle successful uploads on complete
    // For instance, get the download URL: https://firebasestorage.googleapis.com/...
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
    //signup() is the node js signup endpoint
      signup(dispatch ,{email , password , username , phonenumber , profile:downloadURL});
      })
    });

  }

Image field:


<input type="file" name="file" id="file" onChange={(e)=>setfile(e.target.files[0])} />

If is needed to upload any other part of the code please let me know

Upvotes: 0

Views: 194

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

Based on the comments under your question you get a 403 error because your Security Rules prevent any user to upload a file (allow read, write: if false;). This is also a point listed by @eugenemusebe in his answer.

You need to adapt your Security Rules in such a way the desired users have the correct access right for writing:

For example a user needs to be authenticated to upload an image:

service firebase.storage {
  // The {bucket} wildcard indicates we match files in all Cloud Storage buckets
  match /b/{bucket}/o {
    // Match filename
    match /filename {
      allow read: if <condition>;
      allow write: if request.auth != null;
    }
  }
}

More details in the Security Rules documentation.


Note that for testing (and confirming that this is the problem) you can (temporarily) open the write access with:

service firebase.storage {
  // The {bucket} wildcard indicates we match files in all Cloud Storage buckets
  match /b/{bucket}/o {
    // Match filename
    match /filename {
      allow read: if <condition>;
      allow write: if true;
    }
  }
}

Upvotes: 1

Related Questions