How to pass value in Angular form using PUT method for update laravel api?

Laravel PUT method usually used for update, but can’t get data/value from upload file. How to pass value in Angular form using PUT method for update laravel api?

html form:

<form class="w-75" [formGroup]="main_form" (ngSubmit)="onSubmit()" enctype="multipart/form-data">

  <div class="form-row">

<input class="form-control-file" (change)="fileChange($event)" type="file" name="avatar_file" formControlName="avatar_file"

placeholder="Upload file"accept=".png,.jpg,.jpeg,.gif" id="avatar_file">

.ts:

avatar_file: new FormControl(undefined),  //use undefined to avoid console errors
    let form_data = new FormData();
    for (let form_key in this.main_form.value) {
      //console.log(form_key + '=' + this.main_form.value[form_key]);
      if (form_key == 'avatar_file') {
        form_data.append("avatar_file", this.selected_file);
      } else {
        if (this.main_form.value[form_key] !== null) {
          form_data.append(form_key, this.main_form.value[form_key]);
        }
      }
    }
    form_data.append("_method", 'PUT'); // then use post method

......
  fileChange(event: any) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      this.selected_file = file;
      console.warn(fileList);
    }
  }

Leave a Reply

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