Empty formData object during Multiple Image upload in angular 13

Viewed 713

I was trying to upload multiple images using " angular 13 ", But I can't catch the uploaded file in the payload. formData showing empty in the console.

Any idea??

This is the HTML

 <form [formGroup]="myForm" (ngSubmit)="submit()">
    <div class="form-group">
        <label for="file">File</label>
        <input id="file" type="file" multiple class="form-control" (change)="onFileChange($event)">
        <div *ngIf="f.file.touched && f.file.invalid" class="alert alert-danger">
            <div *ngIf="f.file.errors && f.file.errors.required">File is required.</div>
        </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>    

gallery.ts

   onFileChange(event: any) {
    if (event.target.files.length > 0) {
      for (var i = 0; i < (event.target.files.length); i++) {
        this.myFiles.push(event.target.files[i]);
        this.myForm.get('file')?.setValue(this.myFiles);
        console.log('my files check', this.myFiles);
      }
    }
  }   


submit() {
let id = localStorage.getItem('uid');
const formData = new FormData();
for (var i = 0; i < this.myFiles.length; i++) {
  formData.append("file[]", this.myFiles[i]);
}
let payload = {
  'url': '/api/uploadgallery',
  'formData': formData,
  'id': id,
}
console.log('form data check', payload);
this.playerService.postFilegallery(payload).subscribe((response: any) => {
  console.log('resonsecheck', response);
});    

Service.ts

    postFilegallery(sendData: any) {
    console.log('send data check',sendData);
    let headers = {
      'Accept': 'multipart/form-data'     
    };
    return this.http.post(API_URL + sendData.url, sendData, { headers: headers })
      .pipe(map(res => {
        res
        alert('Uploaded Successfully.');
      }));
  }    

enter image description here

1 Answers

I'm not sure why formData property is empty, but I saw that you are attaching multipart/form-data value to the wrong header. Instead of 'Accept': 'multipart/form-data' Try 'Content-Type': 'multipart/form-data'

Related