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.
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:
Thank's to this approach:
Result
.cookie free domains
, advanced caching headers
etc. (ofc you can do that also within Play controller, but...)