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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With