Saturday, August 15, 2009

Display An Image Property In a GSP

This is the first post for the GQuick blog. In this blog I plan to include helpful tips about Grails that we weren't able to get to in the book as well as address questions that come up from readers.

To kick this off we'll look at something that a couple readers of the beta ebook have asked about: Displaying the Sponsor logo in a GSP.

For those who haven't read the book, a bit of background. We have a Sponsor class which represents organizations that might sponsor a technical event. Here's an abbreviated listing of the Sponsor class:
class Sponsor {
byte[] logo

static constraints = {
logo(nullable:true, maxSize:1000000)

This will give us, in most databases, a BLOB type in which we can store an image of our sponsor's logo. Grails' scaffolded views provide the file upload mechanism for us but they don't provide a way to display the stored image in our pages. But don't worry, it's a piece of cake, this is Grails after all.

The first thing we'll do is add an action to our SponsorController called displayLogo.
class SponsorController {

def displayLogo = {
def sponsor = Sponsor.get(
response.contentType = "image/jpeg"
response.contentLength = sponsor?.logo.length

In this action we are retrieving a Sponsor with the id being passed in the params. Then we set a couple properties on the response object that is automatically injected into all Grails controllers. We set the contentType to "image" and the contentLength to the length of the logo property of the Sponsor instance. Finally we write the sponsor.logo to the outputStream of the response. Pretty simple so far.

The next step is to call this action in our GSP. To do this we'll use the createLink tag within an img tag, like so:

<img src="${createLink(action:'displayLogo', id:sponsorInstance?.id)}" />

Now if we drop this in our sponsor/show.gsp in place of the current ${sponsorInstance?.logo} (which spits out a bunch of binary goodness) we will get... an x or a ? depending on which browser we're using. Don't panic, this is just our SecurityFilter trying to help us out. ( For those who haven't read GQuick, we have a SecurityFilter that checks for a logged in user for all actions but those listed in the allowedActions list).

So, let's add displayLogo to the allowedActions list, like this:

def allowedActions = ['show', 'index', 'list', 'login',
                      'validate', 'search', 'displayLogo']
Note: this step is only necessary if you've been following along with the TekDays application in Grails: A Quick-Start Guide. If you are just using this technique in your own application then you're already done.

Now when we view one of our sponsors it will look more like this:


  1. Dave,

    I just started blogging on blogspot and found a link that you might like,

    Just a personal preference but using this makes the blog code easier to read. You might want to consider using for this book site (or not!).