1

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

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.