React append array of objects to formdata

Viewed 1154

I have problem with appending array of objects (object contains file) to formdata. Here is my formdata that I need to send to backend.

{
  education: {
    name: "naziv edukacije ovde celavi",
    company: 1,
    app: 1,
    category: 1
  },
  slides: [
    {
       serial_num: 1,
       text: "test slajda",
       image: File
    },
    {
       serial_num: 2,
       text: "text slajda 2",
       image: File
    }
  ]
}

It works fine for education object when I do

formData.append("education", education)

but slides just doesn't go through console.log of slides array before appending to formData

I tried

formData.append("slides", slides)

which gives me [object Object], [object Object]

If i try

formData.append("slides", JSON.stringify(slides))

image key of object loses most of file data making it not enough for backend

1 Answers

Looks like you're going to have to loop over your array as you append it to your formData, which I saw from a couple places, here & here.

But for your example, you might be able to do something like this:

const slides = [{serial_num: 1, text: "test slajda", image: File}, {serial_num: 2, text: "text slajda 2", image: File}]
const formData = new FormData();
slides.forEach(item => {
  formData.append(`slides`, JSON.stringify(item));
});
console.log(formData.getAll('slides'));
Related