Returning an image stream

236 views
Skip to first unread message

Ian Erickson

unread,
Apr 23, 2013, 2:27:38 PM4/23/13
to reste...@googlegroups.com
I'm looking for a simple example of RestExpress returning a simple image stream (i.e. byte[]).  Can't find anything that matches my needs.  Any help would be appreciated.

Ian

Todd Fredrich

unread,
Apr 30, 2013, 11:21:08 AM4/30/13
to reste...@googlegroups.com
Good Question, Ian.

The best way is to write your byte stream to a ChannelBuffer, then either set the response body to that channel buffer or return it from your controller method.  The second thing you have to do is, on your route definition, set is to not use serialization via a .noSerialization() call.

For example, in your route:
server.uri("/people/{personId}/avatar", controller)
    .noSerialization();

Then in the controller:
public void read(Request req, Response res)
{
   
byte[] bytes = ...
    res
.setBody(ChannelBuffers.wrappedBuffer(bytes);
}

Or, alternatively:
public ChannelBuffer read(Request req, Response res)
{
   
byte[] bytes = ...
   
return ChannelBuffers.wrappedBuffer(bytes);

That should do it...

aman kataria

unread,
Mar 16, 2017, 5:42:07 AM3/16/17
to RestExpress
Thanks this was a life saver!
In Netty 4.0/4.1 ChannelBuffers has been replaced by Unpooled.
Below is the sample code:

import io.netty.buffer.Unpooled;

import java.nio.file.Files;

import java.nio.file.Paths;


response.setContentType("application/pdf"); //Setting content type to be pdf

response.addHeader("Content-disposition", "attachment; filename=" + outputFileAddress);

LOG.info(outputFileAddress);    

//response.setBody(outputFileAddress);    

java.nio.file.Path path = Paths.get(outputFileAddress);

byte[] data = Files.readAllBytes(path);

response.setBody(Unpooled.wrappedBuffer(data));

response.noSerialization(); // No serialization avoids getting the stream to Jackson

response.setResponseStatus(HttpResponseStatus.OK);

Reply all
Reply to author
Forward
0 new messages