My I’m working on a Spring Boot backend with an Angular frontend, and I’m having trouble handling a multipart request. My Angular app needs to send a file along with some JSON data to the backend using FormData.
I have a form in Angular that allows the site admin to upload an image and provide additional data in JSON format. I’m using FormData to append both the file and the JSON string. The request is sent to a Spring Boot REST API endpoint, which expects a MultipartFile and a String parameter.
Angular Code:
Here’s the relevant Angular code that creates and sends the FormData:
form!: FormGroup;
constructor(private fb: FormBuilder, private categoryService: CategoryService) {
this.form = this.fb.group({
name: ['', Validators.required],
description: ['', Validators.required],
categoryImage: ['', Validators.required],
highlights: this.fb.array([
this.fb.group({ highlight: ['', Validators.required] }),
this.fb.group({ highlight: ['', Validators.required] }),
this.fb.group({ highlight: ['', Validators.required] }),
this.fb.group({ highlight: ['', Validators.required] }),
])
});
}
get highlights() {
return this.form.get('highlights') as FormArray;
}
onSubmit() {
if (this.form.valid) {
let formData = new FormData();
const name=this.form.value.name
const description=this.form.value.description
const highlights =this.form.value.highlights
const categoryJSON={
'name':name,
'description':description,
'highlights':highlights
}
formData.append('categoryJSON',JSON.stringify(categoryJSON))
formData.append('file',this.form.value.categoryImage)
console.log('formData', formData)
this.categoryService.createNewCategory(formData)
} else {
alert('Check your data');
}
}
the first console.log():
{ "name": "Graduation", "description": "soem description for testing", "categoryImage": "C:\fakepath\download.jpeg", "highlights": [ { "highlight": "that's a highligh " }, { "highlight": "that's another highligh " }, { "highlight": "that's a third highligh " }, { "highlight": "and the last highligh " } ] }
the second console.log()
{}
And the service call:
createNewCategory(formData: FormData) {
return this.http.post('/api/v1/category/add', formData, {
headers: this.authService.addAuthToHeader()
});
}
public addAuthToHeader() {
let newHeaders = this.headers.set('Authorization', `Bearer ${this.accessToken}`);
return newHeaders;
}
Spring Boot Controller:
Here’s the Spring Boot controller method:
@PostMapping("/add")
public ResponseEntity<Object> addCategory( @RequestParam("file") MultipartFile file,@RequestParam("categoryJSON") String categoryJSON){
return categoryService.addCategory(categoryJSON,file);
}
my CORS Configuration:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type","Content-Range","Accept-Ranges"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/v1/**", configuration);
return source;
}
Problem:
When I send the request, I receive a 400 Bad Request error with the message “Current request is not a multipart request”.