Search code examples
angularfile-uploadangular-reactive-formsform-data

I want to submit a reactive form with multiple images file included


I want to submit a form with multiple images included but I can't append the array of images in file format inside Form data. I have created a reactive form for product entry that will take some product info and multiple images in file format. I get all values from the form but am unable to append the array of images in the image key .so far what I did in submit method

onSubmit() {
    let itemData = this.itemEntryForm.value;
    const formData = new FormData();
    for (const propertyKey of Object.keys(itemData)) {
      if (propertyKey != 'image') {
        formData.append(propertyKey, itemData[propertyKey]);
      } else if (propertyKey == 'image') {
        for (let i = 0; i < itemData[propertyKey].length; i++) {
          formData.append('image', itemData['image'][i]);
        }
      }
    }
    //for console formdata
    formData.forEach((value, key) => {
      console.log(key + '--' + value);
    });
  }
}

I need to store images array inside the image key. stackblitz Code Example


Solution

  • Form your else if block, we initialise a variable as an empty array to store all the images so we can append that to the image after the loop is complete. However, I don't think array of images can be appended to formData hence the JSON.stringify()

        else if (propertyKey == 'image') {
        const imageList = [];
        for (let i = 0; i < itemData[propertyKey].length; i++) {
           imageList.push(itemData['image'][i]);
        }
          formData.append('image', JSON.stringify(imageList));
        }