7

Is there an easy way to process the body of a POST HTTP request as an InputStream when using PostMapping in a Spring Boot RestController?

It is quite simple to accept file uploads from Multipart HTTP POST requests as MultipartFile instances, but I would like to be able to simply post binary content to an HTTP endpoint and process this as an InputStream.

Is this possible with Spring Boot?

For example with the following Postman POST:

enter image description here

Attila
  • 3,206
  • 2
  • 31
  • 44

2 Answers2

9

I know two possible ways

Take HttpEntity

@PostMapping
public ResponseEntity<String> post(HttpEntity<byte[]> requestEntity) {
    return ResponseEntity.ok(new String(requestEntity.getBody()));
}

Take whole Request

@PostMapping
public ResponseEntity<String> post(HttpServletRequest request) {
    request.getInputStream();
}
Matthias
  • 1,378
  • 10
  • 23
6

If you just have an InputStream parameter on your method then you get the request body.

@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<Void> put(InputStream is) {
    // Do something
    return ResponseEntity.ok();
}

This is with Spring Boot 2.4.1.

Matthew Buckett
  • 4,073
  • 1
  • 36
  • 28