Search code examples
grailsplayframework-2.0grails-controller

display photos in grails vs playframework


I have been doing some tests using Grails framework and now I'm trying to do something similar in playframework.

Basically, I want to display some pictures, but to hide (in order to be able to avoid any crawling and to be able to change the hosting ) the pictures path.

The gsp page:

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

The controller:

def displayImage() {
        File image = new File(IMAGES_DIR.absolutePath +'/' + params.img)
        if(!image.exists()) {
            response.status = 404
        } else {
            response.setContentType("application/jpg")
            OutputStream out = response.getOutputStream();
            out.write(image.bytes);
            out.close();
        }
}

The html generated page it looks like:

<img class="thumbnail" src='/myhost/images/displayImage?img=blabla.jpg' />

My questions:

  • Is this a best way to do it ?

  • Regarding the performance ?

  • Is this slower than juste displaying the pictures using http ?

  • Can I do something like this in Playframework ? If yes, how ?

Thanks.

C.C.


Solution

  • For static and public resources most probably using raw HTTP server will be fastest solution, so I don't think it's required to "drag" it through Java controller. Actually you can do it with Play very similar, but even easier - as Play allows yo to return a File as a response body directly ie (written from top of my head):

    public static Result displayImage(String imagePath) {
        File image = new File(SOME_CONFIGURED_FOLDER_WITH_IMAGES +'/' + imagePath)
        if(!image.exists()) return notFound();
        return ok(image).as("image/jpg");
    }
    

    Anyway, you should use it only if:

    • You are not gonna to use additional HTTP server (remember, that Play has built in one?)
    • You need to bring some access control
    • You want to perform some operations, ie. scaling, cropping etc. (in such case, IMHO it's also better to use Play only for creating the thumbnail, and serve it with common HTTP server...)

    Thank's to this approach:

    • You don't waste processor's resources, as HTTP server just need to serve the file which is stored on disk, instead of rewriting it to the Result.
    • Your app can concentrate on other dynamic operations so it's faster.
    • You can (and should) use typical webmaster's techniques for optimizing serving static contents, like cookie free domains, advanced caching headers etc. (ofc you can do that also within Play controller, but...)