Using Grails as a CMS, often times you want your users to add and remove files to a page similar to the way assets are attached to a page in the Confluence Wiki. I recently had to write a controller to handle files upload and download, and thought it might be interesting to share this since it is done so often in the Grails world.
Download the controller : FileResourceController.groovy
Download the view : list.gsp
Download complete sample app : uploader.zip
( to run: install grails. Invoke grails run-app. Navigate to http://localhost:8080 )
Usage- copy the list.gsp into your grails-app/views/fileResource/ directory, and your controller into grails-app/controllers
Config- Define a variable called images.location in conf/config.groovy
There are three methods in the controller:
- list -> gets a list of files = File.list()
- upload -> uploads a file chosen by the user
- delete -> removes chosen file = File.delete()
There are some choices made in the views
- The path to the file was written into a textarea to facilitate copy and paste.
- The views preview in a new window using HTML links to maximize cross browser compatibility.
- File upload goes first, since we don’t know how many items are in this list.
What’s could be improved?
- A more robust solution would integrate both a hierarchical directory structure or allow you to navigate up and down directories or specify an initial directory.
- Version control for files would be nice, similar to the grails.org wiki.
- Ideally, updates to this list would be AJAX based so you can include this page into a modalbox
- Pagination and sorting of files based on file properties.