简体   繁体   English

如何接收请求正文数据以及多部分图像文件?

[英]How to receive request body data along with multi-part image file?

I want to receive multi-part image file with request body data, but could not able to figure it out, why it is throwing org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported exception我想接收带有请求正文数据的多部分图像文件,但无法弄清楚,为什么它会抛出org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported exception

Below is my implementation下面是我的实现

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

EDIT: This is my postman configuration编辑:这是我的 postman 配置

在此处输入图像描述

Since you're sending data in form-data which can send data in key-value pairs.由于您以表单数据的形式发送数据,它可以以键值对的形式发送数据。 Not in RequestBody so you need to modify your endpoint like this:不在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);
}

You need to receive your UserDTO object in String representation and then map it to UserDTO using ObjectMapper .您需要以String表示形式接收UserDTO object,然后使用ObjectMapper将 map 接收到UserDTO This will allow you to receive MultipartFile and UserDTO using form-data.这将允许您使用表单数据接收MultipartFileUserDTO

As per your exception: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' the method is not expecting a multipart data so,根据您的例外情况: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream'该方法不需要多部分数据,因此,

Specify request to consume MultiPart data in @RequestMapping configuration:@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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM