Spring Controller @RequestBody with file upload is it possible?

前端 未结 5 1608
说谎
说谎 2020-12-12 23:55

I have a Controller like this and I want to submit a form with file uploading as well as some form data like label as shown below. Also, I want to do that using @RequestBody

5条回答
  •  别那么骄傲
    2020-12-13 00:42

    I couldn't find a way to use @RequestBody.

    However, you can do something like this:

    @RequestMapping(value = "/uploadStuff", method = RequestMethod.POST)
    public MyViewDto doStuff(@RequestPart("json") @Valid MyDto dto,
                             @RequestPart("file") MultipartFile file) { ... }
    

    You can test it like this:

    MockMultipartFile jsonFile = new MockMultipartFile("json", "",
                "application/json", "{}".getBytes());
    MockMultipartFile dataFile = new MockMultipartFile("file", "foo.zip", "application/octet-stream", bytes);
    
    mockMvc.perform(fileUpload("/uploadStuff")
                .file(dataFile)
                .file(jsonFile))
                .andExpect(status().isOk());
    

提交回复
热议问题