Required request part 'file' is not present in Spring Boot

I checked all of the simular posts and still couldnt find the solution.

Problem is Required request part 'file' is not present in test class.

I want to upload a file and save it to the database. Here is my rest controller @RestController:

@PostMapping(value = "/upload")
public ResponseEntity<LogoDto> uploadLogo(@RequestParam("file") MultipartFile multipartFile) {
   return ResponseEntity.ok(logoService.createLogo(multipartFile));
}

and my test class:

@Test
public void createLogo2() throws Exception {
    String toJsonLogoDto = new Gson().toJson(logoDto);
    MockMultipartFile file = new MockMultipartFile("path", "url", MediaType.APPLICATION_JSON_VALUE, image);
    LogoDto response = LogoDataTest.validLogoDto();
    Mockito.when(logoServiceMock.createLogo(Mockito.any(MultipartFile.class))).thenReturn(response);
    mockMvc.perform(MockMvcRequestBuilders.multipart("/brand-icon/upload")
            .file(file)
            .content(MediaType.APPLICATION_JSON_VALUE)
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .characterEncoding(CharEncoding.UTF_8))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.status().isOk());
}

and my application.yml looks like this:

spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 2MB
      max-request-size: 10MB
      

I tried to add consumes in my @PostMapping; try to set literally every MediaTypes.. still get an error.

I appreciate all of your answer.

Upvotes: 3

Views: 12362

Answers (1)

Vasyl Sarzhynskyi
Vasyl Sarzhynskyi

Reputation: 3955

issue is in declaration of MockMultipartFile, first parameter should match controller @RequestParam param. So, in your case, should be:

MockMultipartFile file = new MockMultipartFile("file", "url", MediaType.APPLICATION_JSON_VALUE, image);

Also, I recommend to update your controller method to the following one:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<LogoDto> uploadLogo(@RequestPart("file") MultipartFile multipartFile) {
    ...
}

Upvotes: 6

Related Questions