My api return error 403 when i try to send a file + object from angular. once i remove the object from angular ts and also from my backend api then i send only the file it works. i think i have a problem in the way i send formData. the car is my object that contains name and desscription.
I'm using angular 17
TS
addCar(carForm: NgForm) {
const carFormData = this.prepareFormDate(this.car);
this.carService.addCar(carFormData).subscribe(
(response: Car) => {
console.log(response);
carForm.reset();
},
(error: HttpErrorResponse) => {
console.log(error);
}
);
}
prepareFormDate(car: Car): FormData {
const formData = new FormData();
formData.append(
'car',
new Blob([JSON.stringify(car)], {type: 'application/json'})
);
for(var i=0; i < car.carImages.length; i++) {
formData.append(
'imageFile',
car.carImages[i].file,
car.carImages[i].file.name
);
}
return formData;
}
onFileSelected(event: any) {
if(event.target.files) {
const file = event.target.files[0];
const fileHandle: FileHandle = {
file: file,
url: this.sanitizer.bypassSecurityTrustUrl(
window.URL.createObjectURL(file)
)
}
this.car.carImages.push(fileHandle);
}
}
}
My service :
public addCar(car: FormData) {
return this.httpClient.post<Car>(`${API_URL}/car/addCar`, car);
}
Spring boot
@PostMapping(value = "/addCar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<CarEntity> addNewCar(@RequestPart("car") CarEntity car,
@RequestPart("imageFile") MultipartFile[] file) throws IOException {
log.info("[addNewCar]");
Set<ImageEntity> images = carService.uploadImages(file);
car.setCarImages(images);
CarEntity carEntity = carService.addNewCar(car);
return ResponseEntity.status(HttpStatus.OK).body(carEntity);
}
is there a probleme with the data i send from angular ?