Spring Controller @RequestBody with file upload is it possible?

前端 未结 5 1604
说谎
说谎 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:35

    You can actually simplify your life here since all you are doing is submitting a form that contains some fields and file. You don't need @RequestBody for what you are trying to do. You can use regular Spring MVC features, so your controller method would look like:

    @ResponseBody
    public WebResponse updateEUSettings(
         Locale locale, 
         @Valid EUPSettingsWrapper endUserPortalSettingsWrapper, 
         @RequestParam(value = "file1", required = true) MultipartFile logo
    ) {
    
    
    }
    

    The client that submits the request to this controller will need to have a form with enctype="multipart/form-data".

    In your Spring MVC test you would write something like this:

    getMockMvc().perform(fileUpload(uri).file("file1", "some-content".getBytes()) 
                            .param("someEuSettingsProperty", "someValue")
                            .param("someOtherEuSettingsProperty", "someOtherValue")
                            .accept(MediaType.APPLICATION_JSON)
                            .contentType(MediaType.MULTIPART_FORM_DATA))
                            .andExpect(status().isOk());
    

提交回复
热议问题