如何接收请求主体数据以及多部分图像文件?
How to receive request body data along with multi-part image file?
我想接收包含请求正文数据的多部分图像文件,但无法弄清楚,为什么会抛出 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);
}
编辑:
这是我的邮递员配置
根据您的例外情况: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);
}
因为您在 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
。这将允许您使用表单数据接收 MultipartFile
和 UserDTO
。
我想接收包含请求正文数据的多部分图像文件,但无法弄清楚,为什么会抛出 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);
}
编辑: 这是我的邮递员配置
根据您的例外情况: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);
}
因为您在 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
。这将允许您使用表单数据接收 MultipartFile
和 UserDTO
。