Search code examples
angularform-data

FormData append File does not work Angular


I'm using FormData to send image to PHP API. When I use this code it does not work:

HTML Code :

<input type="file" name="file" id="file" (change)="onFileSelected($event)" />
<button pButton (click)="onUpload()" label="UPLOAD"></button>

TS Code :

onFileSelected(event) {
    this.uploadFile = event.target.files[0];
    console.log(this.uploadFile);
}

onUpload() {
    const formData = new FormData();
    formData.append('myfile', this.uploadFile, this.uploadFile.name);
    console.log(formData);
}

When console.log(this.uploadFile) i get : enter image description here

and console.log(formData) i get :

enter image description here


Solution

  • There are no issues with your code. Trying to console.log formdata will always give an empty object.

    To display your filedata change your console.log to

    console.log(formdata.getAll('myfile'));
    

    The above function will return an array with your file object blob.

    You can also refer to the MDN documentation for all the other formData functions