Search code examples
imagegrailsgsp

grails display images in folder


I'm trying to do a Grails webapp and now I'm trying to display all images in a folder.

To do that I have the following:

def display(){
        def dir = new File("/tmp/images")
        def list = []
        dir.eachFileRecurse() { file ->
            def avatarFilePath = new File(file.path)
            response.setContentType("application/jpg")
            OutputStream out = response.getOutputStream();
            out.write(avatarFilePath.bytes);
            out.close();
        }
    }

So using the code above I'm displaying one image using:

<img class="thumbnail" src='${createLink(controller: "images", action: "display")}' />

Using this code, I'm displaying one image. How do I display all images in that folder? Do I need to build a list? A list of what? A list of outputstream? In that case, what should I put in my gsp file?


Solution

  • If the images folder was inside the app structure you could just create links to the image directly. In this case I think you need a controller action that output the contents of one file, and another action that get's the list of the images and request the file content.

    class MyController {
      private static final File IMAGES_DIR = new File('/tmp/images')
    
      //get the list of files, to create links in the view
      def listImages() {
        [images: IMAGES_DIR.listFiles()]
      }
      //get the content of a image
      def displayImage() {
        File image = new File(IMAGES_DIR.getAbsoluteFilePath() + File.separator + params.img)
        if(!image.exists()) {
          response.status = 404
        } else {
          response.setContentType("application/jpg")
          OutputStream out = response.getOutputStream();
          out.write(avatarFilePath.bytes);
          out.close();
        }
      }
    
    }
    

    And your gsp could do something like

    <g:each in="${images}" var="img">
      <img class="thumbnail" src='${createLink(controller: "myController", action: "displayImage", params:[img: img.name])}' />
    </g:each>
    

    P.S: the code is not tested, may need some adjust.