0

I have a javascript array which looks like this:

var items = [{
   ID: "1"
   count:'1',
   File: (binary file)
   },
   {
   ID: "2"
   count:'2',
   File: (binary file)
   }
]

I want to get the file input in the backend hence I have to use multipart + formData but I couldnt find a way to convert the list into it. May I know how can I achieve this? Thanks in Advance.

Hanyi Koh
  • 327
  • 1
  • 4
  • 15
  • Does this answer your question? [Convert JS Object to form data](https://stackoverflow.com/questions/22783108/convert-js-object-to-form-data) – Justinas Oct 05 '21 at 11:50
  • Not really, I think my case quite different since I have binary file as property of object and I not just converting single object to formdata + I not using jquery – Hanyi Koh Oct 05 '21 at 14:58
  • You do it same way. Plus `FormData` is not jQuery. – Justinas Oct 05 '21 at 20:31

1 Answers1

0

You can do this

var items = [
    {
        ID: "1",
        count: "1",
        File: "file",
    },
    {
        ID: "2",
        count: "2",
        File: "file",
    },
];

var myFormdata = new FormData();

myFormdata.append("firstId", items[0].ID);
myFormdata.append("secondId", items[1].ID);

//in loop
items.forEach((item, idx)=>{
  myFormdata.append("id_" + idx, item.ID)
})
김두호
  • 56
  • 7
  • But then I only append the ID? how about my other properties like count and the binary file – Hanyi Koh Oct 05 '21 at 15:00
  • You can append your data like myFormdata.append("name", data) check out https://developer.mozilla.org/en-US/docs/Web/API/FormData/append – 김두호 Oct 06 '21 at 00:49