首页 > 解决方案 > 如何接收请求正文数据以及多部分图像文件?

问题描述

我想接收带有请求正文数据的多部分图像文件,但无法弄清楚,为什么它会抛出org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream'不支持的异常

下面是我的实现

public ResponseEntity<GlobalResponse> createUser(@Valid @RequestPart("json") UserDTO userDTO ,@RequestPart(value ="file", required=false)MultipartFile file) throws IOException {

      //Calling some service

      return new ResponseEntity<>( HttpStatus.OK);
}

编辑:这是我的邮递员配置

在此处输入图像描述

标签: javaspring-bootmultipartform-data

解决方案


由于您以表单数据的形式发送数据,它可以以键值对的形式发送数据。不在,RequestBody所以你需要像这样修改你的端点:

@PostMapping(value = "/createUser")
public ResponseEntity createUser(@RequestParam("json") String json, @RequestParam("file") MultipartFile file) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    UserDTO userDTO = objectMapper.readValue(json, UserDTO.class);
    // Do something
    return new ResponseEntity<>(HttpStatus.OK);
}

您需要以表示形式接收UserDTO对象,String然后将其映射到UserDTOusing ObjectMapper。这将允许您接收MultipartFileUserDTO使用表单数据。


推荐阅读