Spring Boot controller - Upload Multipart and JSON to DTO

前端 未结 8 1127
南旧
南旧 2020-11-28 05:16

I want to upload a file inside a form to a Spring Boot API endpoint.

The UI is written in React:

export function createExpense(formData) {
  return         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 05:26

    Remove this from the react front end:

     'Content-Type': 'application/json'
    

    Modify the Java side controller:

       @PostMapping("/{groupId}")
       public Expense create(@RequestParam("image") MultipartFile image,  @RequestParam("amount") double amount, @RequestParam("description") String description, @RequestParam("title") String title) throws IOException {
             //storageService.store(file); ....
              //String imagePath = path.to.stored.image;
             return new Expense(amount, title, description, imagePath);
     }
    

    This can be written better but tried keeping it as close to your original code as much as I could. I hope it helps.

提交回复
热议问题