我想接收包含请求正文数据的多部分图像文件,但无法弄清楚,为什么会抛出okay
不支持的异常
下面是我的实现
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream'
编辑: 这是我的邮递员配置
答案 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
。这将使您可以使用表单数据接收MultipartFile
和UserDTO
。
答案 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);
}