Samstag, 20. Juni 2009

Stripes Image Streamingresolution

I'm often asked how to stream an image from sources like a database blob or a folder which is not shared by the servlet container to the client using stripes. This is done by extending the class net.sourceforge.stripes.action.StreamingResolution. The most simple way:
public Resolution view( ) {
  ...
  String mimeType = getContext().getServletContext().getMimeType(fileName);
  final byte[] file = readFileToByteArray(absolutFilePath);//this method needs to be implemented
  return new StreamingResolution(mimeType) {
     @Override
     protected void stream(HttpServletResponse response) throws Exception {
        response.getOutputStream().write(file);
     }
  };
}
When streaming static content I'd recommend a more complex solution using headers to modify file names or caching behavior of the browser:
public Resolution view( ) {
  ...
  String mimeType = getContext().getServletContext().getMimeType(fileName);
  final byte[] file = readFileToByteArray(absolutFilePath);//this method needs to be implemented
  return new StreamingResolution(mimeType) {
     @Override
     protected void stream(HttpServletResponse response) throws Exception {
        setFilename("TheHolyHandGranade.gif");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 30);
        Date expires = calendar.getTime();
        response.setDateHeader("Expires", expires.getTime());
        response.getOutputStream().write(file);
     }
  };
}
Hope this helps :-)

Kommentare:

rosh hat gesagt…

Why would you want to read the file into a byte array instead of streaming it directly?

Also what scientific approach did you use to calculate the expires-date?

Richard Hauswald hat gesagt…

You're right, streaming the file directly is the less silly approach.

Calculating the expires date is a little bit out of the scope of this article. The number of 30 days from now was just a result of my.heads.util.Random class :-)

A rule of thumb is that setting the expires date to tomorrow will increase performance and decrease server load in most cases. The performance gain in setting it more deep into the future won't be that hight.

If you are interested in this topic you can find a very nice article here: http://developer.yahoo.com/performance/rules.html . Look for the part called "Add an Expires or a Cache-Control Header".

rosh hat gesagt…

don't know if that applies here but in standard servlets the response also hints the buffer size used.

  © Blogger template 'Morning Drink' by Ourblogtemplates.com 2008

Back to TOP