I have a form that submits author, context and images (recently added) in Angular. When I output the data sent over, I was able to get author and context, however I cannot get images (it always display null).
=== SpringBoot ===
Model:
public class Content {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String context;
private String author;
private String images;
public Long getId() { return id; }
public String getContext() { return context; }
public String getAuthor() { return author; }
public String getImage() { return images; }
}
Controller:
@PostMapping("/create")
@ResponseBody
public Content saveContent(@ModelAttribute Content content){
System.out.println(content.getImages());
System.out.println(content.getAuthor());
return null;
}
=== Angular ===
home.component.ts:
submitForm() {
const formData = new FormData();
formData.append('author', 'John Smith');
formData.append('images', 'sample.png');
this.http.post<any>('/create', formData).subscribe({
next: (data) => {
console.log('Success');
},
error: (err) => {
console.log(err);
},
})
}
=== MySQL ===
Database columns
2
Answers
The second parameter in angular post request is body.
Because of that you need to use in your spring controller another annotation RequestBody instead ModelAttribute.
If you are using Angular as a client, so your backend should expose rest APIs to let the clients able to consume them.
To fix your issue you have to follow these steps:
1) First of all, you have to use a RestController and not a simple controller to map the response into a view. Your controller must be annotated with @RestController
2) Change your code like this (bind a request body using the annotation @RequestBody)
3) Create a class called
Content
to define the fields that your backend expects like this4) Change your Angular code to pass directly a request body and not using a FormData
}