0

I want to convert Object Array to Formdata in Angular. My object array can contain any key value pair and image as well.

I, then have to send this formdata via POST API to backend(Express).

[{uid: "", image: File, description: "store", price: "800"}
 {uid: "f9b37f48-cff0-44f1-aa9f-fb9766bde90b", description: "wooden sandals", price: "100"}
 {uid: "dd5adebf-06c6-4d6c-b005-2fcb0a2ca161", description: "blanket", image: File}]

I've tried alot of options but anable to achieve this.

How this conversion can be done?

Or, if I can directly send this Object Array to POST call from Angular?

EDIT 1: image: File is a File object: enter image description here

And upload image:

onUploadImage(imageInput: HTMLInputElement, i, id: string) {
    if(imageInput.files && imageInput.files[0]) {
      this.image = imageInput.files[0]
      if(this.collections[i]['image'] === "" || typeof this.collections[i]['image'] === 'string') this.collections[i]['image'] = this.image
      let result = this.collectionsToAdd.some(item => item['uid'] === id)
      if(result) {
        const index = this.collectionsToAdd.indexOf(this.collectionsToAdd.find(item => item.uid === id))
        this.collectionsToAdd[index]['image'] = this.image
      }
      else {
        const obj = {
          uid: id,
          image: null
        }
        obj.uid = id
        obj.image = this.image
        this.collectionsToAdd.push(obj)
      }

      this.reader.readAsDataURL(imageInput.files[0])
      this.reader.onload = (event) => {
        this.collections[i]['imagePath'] = event.target.result
      }
    }
  }

Thanks in advance!

Prachi Sharma
  • 331
  • 1
  • 5
  • 14
  • `image: File` seems suspect – Maxime Helen Jul 30 '20 at 06:33
  • @MaximeHelen It is the image I'm uploading via frontend. This will be sent as a file to backend so that to store it in S3 – Prachi Sharma Jul 30 '20 at 06:35
  • well you could `JSON.stringify(array)` and in the backend if you use Express.js or php or whatever you parse it back to an array – bill.gates Jul 30 '20 at 06:51
  • How you want to send the data from frontend , totally depends on how the express api is expecting and processing the data ? Convert object to formdata check this https://stackoverflow.com/questions/22783108/convert-js-object-to-form-data – Harmandeep Singh Kalsi Jul 30 '20 at 06:52
  • @Ifaruki I've already tried this but it makes image as an empty object at backend. – Prachi Sharma Jul 30 '20 at 06:54
  • @HarmandeepSinghKalsi As per your link, I've done this before. This solution will depend upon the indexing of my data like 1st uid will have data after that and not before. What I want is to send the data exactly in the way I'm getting here to the backend. Or if any better approach? I'll change my backend accordingly. – Prachi Sharma Jul 30 '20 at 06:56
  • Have you tried this snippet? https://gist.github.com/ghinda/8442a57f22099bdb2e34 Omg this formdata data structure seems really weird to me for nested objects, I wonder why such choice – Maxime Helen Jul 30 '20 at 06:57

2 Answers2

0

You can try this one. Here data is your array.

const formData = new FormData();

for(let i = 0; i < data.length; i += 1) {
    Object.keys(data[i]).forEach((key: string) => {
        if(key === 'image') {
            formData.append(key, JSON.stringify(data[i][key]))
         } else {
             formData.append(key, data[i][key])
         }
    })
}
DonJuwe
  • 4,477
  • 3
  • 34
  • 59
deepak
  • 1,390
  • 1
  • 8
  • 12
0

I think the easiest way you can do this is with multiple HTTP request, here's the simple code

// your array object
let preBody = [{uid: "", image: File, description: "store", price: "800"},
  {uid: "f9b37f48-cff0-44f1-aa9f-fb9766bde90b", description: "wooden sandals", price: "100"},
  {uid: "dd5adebf-06c6-4d6c-b005-2fcb0a2ca161", description: "blanket", image: File}];

// take a array of form data
let formDataArray: FormData[] = [];

// append each object key - value in formDataArray
preBody.forEach((object, index)=>{
  formDataArray.push(new FormData());
  Object.keys(object).forEach((key)=>{
    formDataArray[index].append(key, object[key]);
  });
});

// send request for each formData
formDataArray.forEach((formData)=>{
  this.http.post('http://localhost/test/text.php', formData).subscribe();
});

Note: Your array object should not contain any object or array.

I hope, it may help

Abhijit
  • 382
  • 3
  • 10