Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey REST service to return both jpeg and png images

I am trying to have a single Jersey REST service that could return an image of either a jpeg type or a png type , the reason is because the service only has access to and is returning binary data and cannot tell if its a jpeg image or a png image .

If I use the following declaration the browser displays binary data .

@Produces("image/*")

However if I use the following for jpeg images the correct image is displayed.

@Produces("image/jpeg").

I want to know how I could use a single declaration that would make the browser identify the right type of image(jpeg or png) to be rendered?

like image 373
user1965449 Avatar asked Oct 26 '25 14:10

user1965449


2 Answers

According to JAX-RS specification it is allowed to list multiple media types:

@Produces({"image/png", "image/jpeg", "image/gif"})

see: https://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/Produces.html

Update: for more details see @forty-two 's answer too.

like image 181
ioseb Avatar answered Oct 28 '25 05:10

ioseb


If the service doesn't know the type, it cannot be any more specific than image/*. But, you could inspect the first few bytes of the data to detect the type and add Content-Type header accordingly.

Note that the purpose for having more than one @Produces annotation is for content negotiation, where the user agent express the wanted resource representation and the server answers with an appropriate variant of the data, e.g. JPEG or PNG.

like image 44
forty-two Avatar answered Oct 28 '25 07:10

forty-two



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!