Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To return an object with a binary field in Spring REST, you can use the ResponseEntity class with the MediaType set to APPLICATIONOCTETSTREAM. This will allow you to return a binary file as the response body.

For example, let's assume you have a binary field in your object called "image". You can return the object as follows:

@GetMapping("/image")
public ResponseEntity<byte[]> getImage() {
   YourObject object = yourService.getObjectWithBinaryField();
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   return new ResponseEntity<>(object.getImage(), headers, HttpStatus.OK);
}

In this example, the object's image field is returned as a byte array in the response body. The HttpHeaders object is set to specify the MediaType as APPLICATIONOCTETSTREAM. The ResponseEntity object is returned with the byte array, headers, and HTTP status code.