如何接收多部分图片文件的请求体数据?
如何接收多部分图片文件的请求体数据?
我想接收带有请求体数据的多部分图像文件,但是不知道为什么它会抛出“org.springframework.web.HttpMediaTypeNotSupportedException:Content type \'application / octet-stream\'
”不支持的异常
以下是我的实现
public ResponseEntity createUser(@Valid @RequestPart("json") UserDTO userDTO ,@RequestPart(value ="file", required=false)MultipartFile file) throws IOException { //Calling some service return new ResponseEntity<>( HttpStatus.OK); }
编辑:
这是我的Postman配置
admin 更改状态以发布 2023年5月24日
根据您的异常:org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream'
,该方法不期望接收多部分数据,因此,请在@RequestMapping
配置中指定请求来消耗MultiPart
数据:
@Postmapping("/api/v1/user", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntitycreateUser(@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); }
您需要以字符串
表示接收UserDTO
对象,然后使用ObjectMapper
将其映射到UserDTO
。这将允许您使用form-data接收 MultipartFile
和 UserDTO
。