Search code examples
javascriptnode.jsmulter

Send object with files to backend


So i have this problem that i have an object like:

{
   name: "",
   layers: [{
      name: "",
      traits: [{
         name: "",
         file: File
      }]
   }]
}

The problem is i cannot just JSON.stringify(data) and do an formData.append() and send it to the backend because the File cannot get searilized.

I also saw answer to send an array of images like:

formData.append("image", file1)
formData.append("image", file2)
...

But on the backend i will have the problem to put the image back to the right layer and to the right trait index.

Has anybody an idea whats the best way to achieve this goal?


Solution

  • Give each file a unique name (the third argument to append() lets you specify it). Create your data structure using those names instead of files. Serialise the data structure to JSON. Pass the JSON as a parameter in the FormData object.