Search code examples
imagegrailsgsp

how to display images in Grails?


I am trying to render the images from /WEB-INF/images/sps in the GSP page using the following code:

def index = {
    def baseFolder = grailsAttributes.getApplicationContext().getResource("/").getFile().toString()
    println baseFolder
    def imagesFolder = baseFolder + '/images/sps'
    println imagesFolder
    def imageList1 = new File(imagesFolder).list()
    println imageList1
    def imageList = Arrays.asList(imageList1)       
    println imageList
    imageList
    //redirect(action:"displayImages", params:["imageList":imageList])
    //render(view:"displayImages")
}

The controller is able to read the images from the fileSystem. But when I try to display them using the following code, the images are not coming.

index.gsp

<g:each in="${imageList}" var="image">
   <img src="${resource(dir: 'images', file: image.filename)}" alt="Grails"/>
</g:each>

What mistake am I doing?

EDIT:

When I try with single image, it is working fine - I am able to view the image that is in the WEB-INF/images folder

<img src="${resource(dir: 'images', file: '1.jpg')}" alt="Grails"/>

And there is no HTML code thats getting generated for the loop code(above index.gsp code). Its just blank.

My requirement is to display all the image files that are on the file system folder.


Solution

  • It was simpler. You should return a model from an action as a Map: [imageList: imageList] for imageList to be available by name in GSP.

    And yes, can you move images folder to web-app - is it OK that all the world can request your images via HTTP?