【问题标题】:Required request part 'file' is not present in Spring BootSpring Boot 中不存在所需的请求部分“文件”
【发布时间】:2020-10-22 07:00:59
【问题描述】:

我检查了所有类似的帖子,但仍然找不到解决方案。

问题是所需的请求部分“文件”在测试类中不存在

我想上传一个文件并将其保存到数据库中。这是我的休息控制器@RestController

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

还有我的测试课:

@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());
}

而我的application.yml 看起来像这样:

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

我试图在我的@PostMapping 中添加消耗; 尝试从字面上设置每个 MediaTypes.. 仍然会出错。

感谢您的所有回答。

【问题讨论】:

    标签: spring spring-boot spring-mvc spring-restcontroller spring-rest


    【解决方案1】:

    问题在于MockMultipartFile 的声明,第一个参数应与控制器@RequestParam 参数匹配。所以,在你的情况下,应该是:

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

    另外,我建议您将控制器方法更新为以下方法:

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

    【讨论】:

      猜你喜欢
      • 2017-04-06
      • 2019-09-08
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多