0

I have a POST request, that I'm sending from my frontend, with axios, where I send a FormData object, with an array of files, and some additional parameters

   const files = this.state.fileObjects
    const fields = {
        "name": this.state.name,
        "email": this.state.email,
        "message": this.state.message
    }

    const data = new FormData()
    //implement multer on server side
    for (const [index, file] of files.entries()) {
        data.append(`files[${index}]`, file)
    }
    for (const [key, value] of Object.entries(fields)){
        data.append(key, value)
        console.log(data)

I then use a post request, to send the data to my backend, where i let multer handle the FormData object

 axios({
        method: 'post',
        url: '/api/form',
        data: data,
        config: { headers: {'Content-Type': 'multipart/form-data' }}
        })
        .then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response)
    })

when everything is appended to the formdata, object nothing is received properly on the backend. What am i doing wrong?

Dedi
  • 2,812
  • 3
  • 22
  • 55
  • Try just writing `data.append('file[]', file)` and see if that helps – Tholle Feb 22 '19 at 09:19
  • `file`, or `files`.. I have an array of files? – Dedi Feb 22 '19 at 09:20
  • Yes, [but you can append multiple files with the `[]` notation](https://stackoverflow.com/questions/12989442/uploading-multiple-files-using-formdata) – Tholle Feb 22 '19 at 09:21
  • I tried looping through the files, and adding them, but there was no output ```files.forEach(file =>{ data.append('files[]', file) }) console.log(data.getAll("files")) //logs empty array``` – Dedi Feb 22 '19 at 09:23
  • Try and send it with `axios.post('/api/form', data)` and see if you get something on the server. – Tholle Feb 22 '19 at 09:24
  • I tried it.. but nothing is received on the server side... – Dedi Feb 22 '19 at 09:27
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/188874/discussion-between-baileyhaldwin-and-tholle). – Dedi Feb 22 '19 at 09:27

0 Answers0