Spring Boot controller - Upload Multipart and JSON to DTO

前端 未结 8 1098
南旧
南旧 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:42

    Add the consumer type to your request mapping .it should work fine.

    @POST
    @RequestMapping("/upload")
    public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile file,consumes = "multipart/form-data") 
    {
        if (file.isEmpty()) {
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        } else {
            //...
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:44

    You have to tell spring you're consuming multipart/form-data by adding consumes = "multipart/form-data" to the RequestMapping annotation. Also remove the RequestBody annotation from the expenseDto parameter.

    @RequestMapping(path = "/{groupId}", consumes = "multipart/form-data", method = RequestMethod.POST)
    public ExpenseSnippetGetDto create(ExpensePostDto expenseDto, 
       @PathVariable long groupId, Principal principal, BindingResult result) 
       throws IOException {
       //..
    }
    

    With the posted ExpensePostDto the title in the request is ignored.

    Edit

    You'll also need to change the content type to multipart/form-data. Sounds like that's the default for post based on some other answers. Just to be safe, I would specify it:

    'Content-Type': 'multipart/form-data'
    
    0 讨论(0)
提交回复
热议问题