skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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)

    @RestController // this is the right annotation to use
    public class ContentController {
      @PostMapping("/create")
      public Content saveContent(@RequestBody Content content){
      //put your persistence logic (save in a database, ...)
      return content;
      }
    }
    

    3) Create a class called Content to define the fields that your backend expects like this

    export class Content {
      author: string;
      images: string;
    }
    

    4) Change your Angular code to pass directly a request body and not using a FormData

    submitForm() {
       const contentRequest : Content = {
        author: 'John Smith',
        images: 'sample.png'
    }
    
     this.http.post<any>('/create', contentRequest).subscribe({
            next: (data) => {
              console.log('Success');
            },
            error: (err) => {
              console.log(err);
            },
        })
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search