0

How I could send files successfully if my payloads look like this?

const payload = {
  documents: [
    { doc_category: someValue, doc_files: [files1.pdf, file2.pdf, file3.pdf] }
  ]
}

I have tried something like this but it is not working

const formData = new FormData()
formData.append('document[0][doc_category]', someValue)
files.forEach((doc, key) => {
   formData.append(`document[0][doc_files][${key}]`, doc)
}

axios.post('/url', formData, {headers: { 'Content-Type': 'multipart/form-data' }})
 .then( // handling response here )

Please Note that I am not asking how to send files using axios, but how to append data to FormData, in which the data is array object containing files.

I have tried JSON.stringfy but it's failed too. Any help would be very appreciated

dede
  • 823
  • 4
  • 13
  • 24
  • Does this answer your question? [How to post a file from a form with Axios](https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios) – Ouroborus Nov 25 '22 at 00:26
  • Hi Ouroborus, I am sorry, I can send the file using axios successfully. My problem at the moment is that I can't send files if the payload format is in array objects. Lot of answer from internet suggesting JSON.stringfy, however, it won't work if the objects contain files. – dede Nov 25 '22 at 04:02
  • 1
    Read the answers to that question more carefully. None of them attempt to convert the files to JSON. I think the key thing to understand is that you won't be able to send the data and the files together in the same structure. – Ouroborus Nov 25 '22 at 04:46
  • Thank you @Ouroborus, I think this question related more https://stackoverflow.com/questions/14026539/can-i-append-an-array-to-formdata-in-javascript – dede Nov 25 '22 at 06:27

0 Answers0