Whenever I try to upload an image, the server keeps throwing an error saying
Cannot read property 'buffer' of undefined
. I am using Node.js as a backend server and interestingly, when I send the image through Postman, it gets stored in MongoDB without any issues.
Despite reading multiple posts on Stack Overflow, I still can't figure out what's causing this error. It seems like I'm missing something crucial here.
// HTML Code
<label for="InputImage">Upload Image</label>
<input type="file" accept="image/*" title="image"
(change)="handleImageInput($event)"
class="form-control" id="InputImage">
// Component.ts
imageToUpload: File;
handleImageInput($event) {
this.imageToUpload = $event.target.files[0];
}
addPackage() {
const obj = this.onSubmit();
const dataToSend = {
...obj,
title: this.packageForm.controls.title.value,
price: this.packageForm.controls.price.value,
};
const formData = new FormData();
formData.append('Image',this.imageToUpload,this.imageToUpload.name);
this.submitted = true;
if (this.packageForm.valid) {
this.submitting = true;
this.submitText = 'Submitting';
this.packageService.addPackage(dataToSend,formData).subscribe(res => {
this.data = res;
if (this.data.status == true) {
this.toasterService.showSuccess('Package added Successfully');
this.reset();
}
}, error => {
console.log(error);
}, () => {
this.submitting = false;
this.submitText = 'Submit';
}
);
} else {
this.toasterService.showFailure('Please fill all the fields');
}
}
// Service.ts
addPackage(packageData: IProduct,imageData) {
console.log(packageData);
return this.http.post(this.apiUrl + 'spectrum/package/addPackage',
{
title: packageData.title,
productNames: packageData.productNames,
productQuantities: packageData.productQuantities,
price: packageData.price
},imageData)
}