I am facing a challenge in uploading form data from Angular to Spring Boot server.
Basically, in Spring Boot, I define the following classes:
data class Photo(
val id: Long = 0L,
val file: MultipartFile
)
data class PostRequest(
@field:Size(min = 1, max = 100)
val title: String,
val photos: List<Photo> = mutableListOf()
)
This is handled via Controller:
fun createPost(@Valid @ModelAttribute postRequest: PostRequest)
In Angular, I have created a form as follows:
this.postForm = this.fb.group({
title: ["", [Validators.required, Validators.minLength(1)]],
photos: this.fb.array([]),
});
When a user uploads a photo, the following lines are executed:
const photosArray = this.postForm.get("photos") as FormArray;
const newPhotoGroup = this.fb.group({
id: "",
file: event.target.result,
});
photosArray.push(newPhotoGroup);
Lastly, a FormData object is constructed:
const formData = new FormData();
formData.append("title", this.postForm.get("title")?.value);
formData.append("photos", this.postForm.get("photos")?.value);
To send this form data to the API, the following function is utilized:
postRequest<T>(url: string, body: any): Observable<HttpResponse<T>> {
const headers = new HttpHeaders({
"Content-Type": "multipart/form-data",
});
return this.http.post<T>(url, body, {
headers,
observe: "response",
withCredentials: true,
});
}
Upon inspecting developer tools, the request appears like this:
https://i.sstatic.net/blz6t.png
However, Spring Boot raises an issue:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
If anyone can provide insight on this matter, it would be greatly appreciated. Thank you.