Search code examples
imagegrailsuploadstatic

Grails: Serving Static Content from outside the application


I'm developing a CMS and I'd like users to be able to upload their own images, CSS files and the like. For the safety of the resources, I do not want to store the uploaded files within the application structure / deployed WAR.

What is the easiest way to serve content in grails, from a controller from a non-grails location?


Solution

  • After much research and questioning, I decided to package the static resources (such as images) in the database. The advantages of this are:

    1. You don't need to package your images within your application (where a redeploy could cause you to lose them all)
    2. You don't need to store your images in another location on the server, away from your application.
    3. You don't need to work with a 3rd party service such as Amazon S3.
    4. Writing a simple controller to serve files from the database is relatively simple.

    The disadvantages are:

    1. You cannot access/manipulate the files on the filesystem.
    2. The database grows and can become very slow.
    3. You need to make a database call every time someone requests an image.

    I decided to go with the solution, even though there are these disadvantages. This is how I dealt with them:

    1. This isn't a problem as it's a 100% online system.
    2. My images are small and there aren't many of them, so this isn't a problem.
    3. Made use of a efficient and easy caching mechanisms. See below:

    I'm using Smart Browser Caching by making use of etags (documentation) and using EHCache (documentation) to cache the images server side. As soon as a new image is uploaded, the e-tag is changed, and the cache is cleared, forcing the browser to download a fresh copy.

    So far, the loss of performance from the MySQL database has been un-noticable, and performance is lightning fast.