Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return image as stream from JAX-RS?

I'm trying to return an image in a JAX-RS web service. I was able to get this successfully working by returning FileInputStream but I'd prefer to avoid creating a File for each request.

I am using Apache CXF and Jackson (all the other resource methods produce application/json).

Code looks like this:

@GET
@Produces("image/png")
public Response getQrCode(@QueryParam("qrtext") String qrtext) {

    ByteArrayOutputStream out = QRCode.from(qrtext).to(ImageType.PNG).stream();

    return Response.ok(out).build();
}

Unfortunately, this produces the dreaded:

org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor:376 - No message body writer has been found for response class ByteArrayOutputStream.

Here's a link to a similar post but it doesn't mention the "No message body writer" issue I'm running into.

I'd appreciate any ideas of how to deal with this issue. Thanks!

like image 986
Justin Avatar asked Aug 24 '12 21:08

Justin


2 Answers

Just use StreamingOutput wrapper. For some reason it is unknown, but it is GREAT for providing, well, streaming output. :-)

like image 142
StaxMan Avatar answered Sep 28 '22 23:09

StaxMan


I think you need to provide an InputStream containing the image in the Response.ok(out) not an OutputStream. (Your JAX-RS framework would read the bytes from the InputStream and put them onto the response, it wouldn't be able to do anything generically with an OutputStream)

(I know you're on CXF, but Jersey's doc: http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e324 and by the JAX-RS spec, the framework must provide a MessageBodyWriter for InputStream.)

Edit: You apparently know about InputStreams being required, d'oh... Do you have control over the QRCode class?

Short term, you might be able to do:

return Response.ok(out.toByteArray()).build();
like image 40
Charlie Avatar answered Sep 29 '22 00:09

Charlie