【问题标题】:How to receive request body data along with multi-part image file?如何接收请求正文数据以及多部分图像文件?
【发布时间】:2020-01-21 08:46:46
【问题描述】:

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

下面是我的实现

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

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

【问题讨论】:

  • 不工作是什么意思?它会引发任何错误吗?请详细说明
  • 请向我们展示您的客户端实现
  • @Mustahsan 它正在抛出 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported exception
  • 可以分享一下你在这个方法上面使用的RequestMapping配置吗?
  • @ValentynRiabukhin 现在,我正在使用 Postman 测试 API

标签: java spring-boot multipartform-data


【解决方案1】:

因为您在 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);
}

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

【讨论】:

  • 你能告诉我,ObjectMapper 类的包名是什么,因为有多个 ObjectMapper 类
  • @camelCode com.fasterxml.jackson.databind
  • @camelCode 我很高兴知道这一点。
  • 您知道任何替代解决方案吗,实际上我想将数据作为@Requestbody 与图像文件一起发送
  • @camelCode 和 @RequestBody 你不能发送MultipartFile
【解决方案2】:

根据您的例外情况:org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' 该方法不需要多部分数据,因此,

@RequestMapping配置中指定消费MultiPart数据的请求:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-10
    • 2021-11-14
    • 2018-09-16
    • 2019-11-06
    • 2018-11-06
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多