How to upload multiple files via Angular and reset file input

<!-- upload files -->

<divclass="input-group mb-3" *ngIf="declaration_status=='Open'">

<divclass="input-group-prepend">

<spanclass="input-group-text"id="basic-addon1">Upload Attachments</span>

</div>

<input class="form-control" #chooseFileInput (change)="fileChange($event)" type="file"name="file" multiple 

placeholder="Upload files"accept=".png,.gif,.jpeg,.pdf,.txt,.csv,.doc,.zip,.gz,.rar"id="choose_file">

<span *ngIf="uploading" class="input-group-text"><i class="fa fa-spinner fa-spin mr-3 ml-2"aria-hidden="true"></i>

Uploading ...</span>

</div>

ts:

fileChange(event: any) {
    let formData = new FormData();
    let fileList: FileList = event.target.files;
    for (let i = 0; i < fileList.length; i++) { formData.append('files[]', fileList[i]); } formData.append('id', String(this.edit_record_id)); this.uploading = true; this.xxxService.upload(formData) .subscribe( result => {
          // console.log('Return Form API:');
          // console.log(result);

          // do something here

        }, error => {
          if (error.error && error.error.message) {
            this.error_msg = error.error.message;
          } else {
            this.error_msg = 'Create Failure, Please report to Admin';
          }
        }
      );

  }

reset file input:

  @ViewChild('chooseFileInput') chooseFileInput: ElementRef;
  uploading = false;
....
  resetSelectFile() {
    this.chooseFileInput.nativeElement.value = "";
    this.uploading = false;
  }

Leave a Reply

Your email address will not be published. Required fields are marked *