Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post an Image and JSON object with single request to back end Spring Boot

Tags:

spring-boot

I want to send image and JSON data to my back end in Spring Boot. This is my method:

@PostMapping
    public void uploadFile(@ModelAttribute FileUploadDto fileUploadDto) {

My FileUploadDto model:

public class FileUploadDto {
    private MultipartFile file;
    private CategoryModel category;

My CategoryModel model:

@Entity
@Table(name = "Category")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CategoryModel {
    @Id
    @Column(name = "id")
    //@GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String category_name;
    private String category_description;
    private String image_path;

    @JsonIgnore
    @OneToMany( mappedBy = "category")
    private Set<ProductModel> category;

I do not understand where I'm wrong.

My postman request: enter image description here

like image 823
SIn san sun Avatar asked Jan 27 '26 21:01

SIn san sun


1 Answers

enter image description here

Your payload has to be raw and in json form. Something like this would help Spring boot to convert your payload into a object of an example class:

public class Foo{
     public String foo;
     public String foo1;

     //Getters setters
}

And the request handling method:

@PostMapping
    public void uploadFile(@RequestBody Foo foo)

It is also recommended to parse the payload into some a temporary class and then convert objects of the temporary class into the Entity class and vice versa. Take a look at: https://struberg.wordpress.com/2012/01/08/jpa-enhancement-done-right/ for more information

Also, if you want to upload file per REST I also recommend you to take a look at the following documentation: https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/

Best luck.

like image 150
curiouscupcake Avatar answered Jan 30 '26 19:01

curiouscupcake