This file upload code was referenced from this source.
The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload.
I have confirmed that the server side code is functioning properly by testing it with Postman.
Below is the HTML section:
<h1>Angular 10 FormData (multipart/form-data) Example</h1>
<div>
<form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">
<div>
<input type="file" name="profile" (change)="onFileSelect($event)" />
</div>
<div>
<button type="submit">Upload</button>
</div>
</form>
</div>
This is the component part:
onSubmit() {
const formData = new FormData();
formData.append('file', this.uploadForm.get('profile').value);
this.http.post<any>(CommonConstants.env+"api/master/upload",formData).subscribe(
(res) => console.log(res),
(err) => console.log(err)
);
}
onFileSelect(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.uploadForm.get('profile').setValue(file);
}
}
After uploading, I noticed that the network tab in Chrome does not display the Content-Type header in Request Headers.