1

I'm currently trying to send my files to my express server but every time I try and send my request the body is empty. After some research, it seems like they would not be stored in req.body so I'm not sure how to actually access the files that I've stored in my formdata.

Clientside code

export default async function UploadToFireStorage(accepetedfiles,fileVals){//Index are 1-1

  const formData = new FormData();
  formData.append('files', accepetedfiles);

  try{

    const response = await fetch(`https://someUrl`,{
      method:"POST",
      body: JSON.stringify(formData)
    })

    const jsonData = await response.json()

    console.log(jsonData) //Attempt to see how my req is formed

  }catch(error){

      console.log(error)

  }

}

express code

app.post('/uploadNewFiles',async(req,res)=>{

try{

    const files = req.? // im not sure what to access after sending my formdata

    for(let file = 0;file < files.length;file++){

        let storageRef = ref(storage, `files/${files[file].path}`);
        let uploadTask = await uploadBytesResumable(storageRef, files[file]);

    }

    res.json(files)

}catch(error){

    res.json('Error: ' + error)

}

})

So just to clarify my question. I know when I make a fetch request I can package data that needs to be sent so I can post it and then extract it using something like let someVar = req.body.someVar and I've tried that with my file array but am unable to get my file array back and i'm not totally sure how to access it from req.

1 Answers1

1

To properly post the files, don't use JSON.stringify. Set the body equal to formData directly. See this answer for more detail.

On the server side, you'll need to use a body parser that can handle multi-part form data, like multer . See this answer for more detail.

lucasvw
  • 1,345
  • 17
  • 36
  • Thanks I'll go ahead and look into this. – boredProjects Dec 07 '22 at 20:34
  • I believe the first bit worked but I know multer doesn't work well with firebase so I'll keep looking for something to handle it. – boredProjects Dec 07 '22 at 22:14
  • @boredProjects I haven't personally worked with firebase before, but it seems like multer should work with it just fine: https://stackoverflow.com/questions/55600971/upload-image-using-multer-to-firebase-storage-issue – lucasvw Dec 08 '22 at 15:52
  • I don't believe it does as this is still an issue on github https://github.com/firebase/firebase-functions/issues/141. Also, I've attempted myself and the req.body etc is always empty due to firebase doing their own preprocessing. – boredProjects Dec 08 '22 at 18:19