Search code examples
javascriptangulartypescriptform-data

How to clear FormData() after submitting


I developed a file input. When selecting that file a function is executed that detects the file and sends it to a service.

My problem is that the format always absorbs all selected files and never cleans. That is, if you select 2 images and later delete one of them, I get 1, but if after deleting one image, insert another one ... I will have 3 and not two (there should be 2 because one of them has been deleted). The problem is that the formdata is always storing everything.

Is there a way to clear formadata whenever a file is inserted?

Example - Stackblitz

code

  <input type="file" id="files" (change)="Add($event)">

  formData1 = new FormData();

 Add(event) {
    var anex = event.target.files;

    for (let index = 0; index < anex.length; index++) {
          this.formData1.append('file', anex[index]);
        }  

        this.sendfiles()
  }

  sendfiles(){
    console.log("Clear formdata();")
    console.log(this.formData1)
  }

Solution

  • You should clear your formData as a new instance before adding new files.

     Add(event) {
        var anex = event.target.files;
        // Clear form data before appending new ones
        this.formData1 = new FormData();
    
        for (let index = 0; index < anex.length; index++) {
              this.formData1.append('file', anex[index]);
            }  
    
            this.sendfiles()
      }