Ask Your Question
1

How can an object with a binary field be returned in Spring REST?

asked 2022-01-10 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-04-12 02:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-10 11:00:00 +0000

Seen: 17 times

Last updated: Apr 12 '21