Tharapong Nitsatong
Tharapong Nitsatong

Reputation: 173

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

Upvotes: 1

Views: 2554

Answers (1)

Vedant Shetty
Vedant Shetty

Reputation: 1717

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

Upvotes: 1

Related Questions