Home > OS >  Trying to upload files to firebase storage but its not working. Error object is empty, how do I figu
Trying to upload files to firebase storage but its not working. Error object is empty, how do I figu

Time:04-12

So i'm trying to send image files uploaded by my users to firebase storage using the file type input element. Like this:

<input
className={inputStyle}
{...register("donorPhotoFile")}
type="file"
accept=".png, .jpg,.jpeg"
></input>
So when I try to console.log the value returned of that input, im getting an object with the following properties:

name: "file_name.jpg",
size: ,
type: "image/png"
webkitRelativePath: ""

The /api/firebase is my api endpoint in next.js to upload my form data to firestore. From the firebase documentation, the 'file' should come from File API which I've did but its always unsuccessful and im not sure what im doing wrong.

  const submitForm = async (data) => {
    const  imageFile = data.donorPhotoFile[0] //this is the file 

    const imageUpload = await fetch("/api/firestorage", {
      method: "POST",
      body: imageFile
    });

    const res = await imageUpload.json()
    console.log(res)
 }
 
 //in my firestorage endpoint  i've done this:
 
 const storage = getStrorage(app) //app here is an instance of my firebase initialized
 
 const handler =  async (req, res) => {
  const storageRef= ref(storage) 
  const imageFile = req.body
  
  try {
    uploadBytes(storageRef, imageFile);
    res.status(200).json({statusRes: "success"})
  } catch(error) {
    res.status(400).json({statusRes: "failed", errorMessage: error})
  }
 }

Doing that returns a storage/invalid-root-operation error code with a message of:

"Firebase Storage: The operation 'uploadBytes' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png')

So tried to make a reference to a specific file and inserted the file name as a second parameter to storageRef like this:

const storageRef = ref(storage).child(`images/${req.body.name}`)

but its still not working but now i'm getting an empty error object so I can't figure out what's wrong now. So i actually tried checking what req.body is and it's returning this: file object in my api endpoint

I don't understand why is it like that? And what im actually looking at? What i've sent in my post request is a File object. Like this: File object i attached to my post request

CodePudding user response:

You can create a reference to a path using Modular SDK as shown below:

const storageRef= ref(storage, `images/${req.body.name}`) 

The .child() method is used in older name-spaced syntax.

  • Related