Tuesday, July 22, 2014

Grails: Displaying image stored in the database on gsp

Here is a Grails implementation of displaying image stored in the database (as byte[]) on gsp.

Notes: 

  • I have spring security core plugin configured
  • The image tag calls the controller's method directly and it uses the apps url and app.name from Config.groovy and application.properties
 FILE: Domain class - SecUser  

 class SecUser extends User {  
      String firstName  
      String middleName  
      String lastName  
     byte [] userPhoto  
      Date dateCreated  
      Date lastUpdated  
      static constraints = {  
       firstName blank: false  
       middleName blank: false  
       lastName blank: false  
       userPhoto nullable: true, maxSize:1024000  
      }  
     String toString() {  
       if(firstName && middleName && lastName){  
         return "${firstName} ${middleName} ${lastName}"  
       } else {  
         return username  
       }  
   }  
 }

 FILE: MyController 
 
      class DashboardController {  
           def springSecurityService  
           def index() {  
                render(view: 'index')  
           }  
           def displayAvatarForCurrentUser() {  
                User user = springSecurityService.getCurrentUser()  
                SartUser sartUser = SartUser.findByUsername(user.username)  
                response.outputStream << sartUser.userPhoto // write the photo to the outputstream  
                response.outputStream.flush()  
           }  
      }  
 FILE: show.gsp  
      <div>  
           <sec:ifLoggedIn>  
                <img src="${grailsApplication.config?.grails?.serverURL}/dashboard/displayAvatarForCurrentUser"/>  
           </sec:ifLoggedIn>  
           %{--If the user has logged in, then the avatar will be shown.--}%  
      </div>  

 FILE: Config.groovy  

      environments {  
           development {  
                grails.logging.jul.usebridge = true  
                grails.serverURL = "http://localhost:9090/${appName}"  
           }  
           test {  
                grails.serverURL = "http://localhost/${appName}"  
           }  
           production {  
                grails.logging.jul.usebridge = false  
                // TODO: grails.serverURL = "http://www.changeme.com/${appName}"  
           }  
      } 
 
 FILE: application.properties  

      app.name=samplegrailsappname  

No comments:

Post a Comment