Search code examples
angularangular-forms

FormData.append() is empty iterating over a FileList


I have difficulty figuring out why formData is returning an empty object when iterating over a list of files and appending them to an empty instance FormData() using formData.append().

MDN https://developer.mozilla.org/en-US/docs/Web/API/FormData/append


component.html

<input type="file" name="image" id="image" multiple accept="image/*" (change)="onImageSelect($event)"/>

component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-image-uploader',
  templateUrl: './image-uploader.component.html',
  styleUrls: ['./image-uploader.component.css']
})
export class ImageUploaderComponent {
  fileList: File[] = [];

  onImageSelect(files: any) {
    const formData = new FormData();

    this.fileList = files.target.files;

    for (const file of this.fileList) {
      formData.append('images[]', file, file.name);
      console.log(file, file.name);
    }
    console.log(formData); // returns an empty {}
  }
}


Solution

  • Always prefer typed alternatives. In this case you could use

    <input #filePicker type="file" ... (change)="onImageSelect(filePicker.files)" />
    

    And then, in the Component class

    onImageSelect(files: FileList): void {
      ...
    
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        formData.append('images[]', file, file.name);
      }
    }
    

    That's it.
    Remember you cannot loop a FileList with a for-of as it lacks the Iterator Symbol.