如何与多部分图像文件一起接收请求正文数据?

时间:2019-09-20 09:45:24

标签: java spring-boot multipartform-data

我想接收包含请求正文数据的多部分图像文件,但无法弄清楚,为什么会抛出okay不支持的异常

下面是我的实现

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream'

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

enter image description here

2 个答案:

答案 0 :(得分:2)

由于您要以 form-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对象,然后使用UserDTO将其映射到ObjectMapper。这将使您可以使用表单数据接收MultipartFileUserDTO

答案 1 :(得分:0)

根据您的例外情况:org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream'该方法不希望包含多部分数据,

指定在MultiPart配置中使用@RequestMapping数据的请求:

@Postmapping("/api/v1/user", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) 
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);
}