boredProjects
boredProjects

Reputation: 343

Passing files from react-dropzone to express server

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.

Upvotes: 1

Views: 884

Answers (1)

lucasvw
lucasvw

Reputation: 1557

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.

Upvotes: 2

Related Questions