Grails File Uploader Plugin

  • Tags: plugin, file uploader
  • Latest: 1.2.1
  • Last Updated: 16 June 2011
  • Grails version: 1.2-M1 > *
  • Authors: null
10 votes
Dependency:
compile ":file-uploader:1.2.1"

 Documentation

Summary

Installation

grails install-plugin file-uploader

Description

Grails File Uploader Plugin

Description

This is a simple plugin to handle file uploads (it have all included, controller, taglibs, etc) with multiple configurations. Each of this configurations can limit upload file size, allowed extensions and set where the files will be stored in the disk.

Download and Sample

The plugin code is hosted in GitHub, and can be downloaded or forked from https://github.com/grails-file-uploader. There you've a sample application(grails-file-uploader-sample) I made to show how to use the plugin and config it. It is availabe at https://github.com/grails-file-uploader/grails-file-uploader-sample. Fell free to fork it and make it better (same for plugin).

Configuring

In your Config.groovy, you'll have to define a structure similar to this:

fileuploader {
	avatar {
		maxSize = 1024 * 256 //256 kbytes
		allowedExtensions = ["jpg","jpeg","gif","png"]
		path = "/tmp/avatar/"
	}
	docs {
		maxSize = 1000 * 1024 * 4 //4 mbytes
		allowedExtensions = ["doc", "docx", "pdf", "rtf"]
		path = "/tmp/docs/"
	}
}

So in this example, we've defined two upload 'groups', avatar and docs, each one with its own path, extensions and max allowed size.

Domain Class

The plugin has one Domain Class to handle uploaded files (UFile.groovy) with some properties you may want to use in your app. It has the properties below:

PropertyWhat is it
sizeThe size of this file (in bytes)
pathWhere the file is stored locally. You won't really need this, since the plugin have a taglib to build links.
namethe filename
extensionif you want to use some images on extensions
dateUploadedWhen the file was uploaded to disk
downloadsHow many times the file was downloaded

You'll need to have one instance of this class inside your DomainClass that holds an instance to this file.

And don't forget to import the class
import com.lucastex.grails.fileuploader.UFile

Domain Class

DownloadController

This controller is called by the taglib download method.

FileUploaderController

This controller is the main controller, to upload files. *Ater the file upload, this controller redirect to action/controller specified ant it will insert in the params map an attribute named "ufileId" with the uploaded UFile id.

show method (in the controller)

With this method it's posible to show the image in the following way :

<img src="${createLink(controller:'fileUploader', action:'show', id:test.id )}" .... />

Obviously the parameter is the UFile id.

Taglibs

The project have one taglib pre-defined (FileUploaderTaglib), for building upload forms, and to build the file download links.

form method

<fileuploader:form	upload="avatar" 
			successAction="success"
			successController="test"
			errorAction="error"
			errorController="test"  id="${test.id}"/>

This will build the upload form, this is the parameters:

NameDescriptionExample
uploadThe name of "configuration" group to this upload form'avatar' or 'docs'
successActionThe action to redirect after a successfull uploadindex
successControllerThe controller to redirect after a successfull uploadsendFile
errorActionThe action to redirect if some error occurserror
errorControllerThe controller to redirect if some error occurssendFile

Due an Grails 1.2-M1 bug , that makes 'action' and 'controller' parameters to be null in taglibs, all parameters are required. As this bug to be corrected, the default values for this parameters will be the current action and controller.

download method

This method will build the download link for the file and have to receive the UFile id as parameter:

<fileuploader:download 	id="${f.id}"
			errorAction="error"
			errorController="mycontroller">download</fileuploader:download>

Parameters:

NameDescription
idUFile id
errorActionThe action to redirect if some error occurs
errorControllerThe action to redirect if some error occurs

prettysize method

You can use this method to prettify your file's size.

<fileuploader:prettysize size="${f.size}" />

it will give you:

File size (bytes)Result
183183b
30003kb
20480002mb
10485760001gb

Service

Method to physically remove the file (in the service)

Just passing the ufile id as parameter the file will be deleted. There 's the code:

def boolean deleteFile(def idUfile) {
    	def borro = false;
    	def ufile = UFile.get(idUfile)
        if (!ufile) {
        	log.error "could not delete file: ${file}"
        	return;
        }
		def file = new File(ufile.path)
		if (file.exists()) {
			if (file.delete()) {
				log.debug "file [${ufile.path}] deleted"
				borro=true;
			} else {
				log.error "could not delete file: ${file}"
			}
		}
		return borro;
    }
}

i18n messages

The plugin has built in support for i18n messages. Right now, the only language packaged within the plugin is English. To translate messages, look into plugin's message.properties inside the plugin.

Available messages
fileupload.upload.nofile = No file was sent, please select the file and try again.
fileupload.upload.fileBiggerThanAllowed = Sent file is bigger than allowed. Max file size is {0} kb
fileupload.upload.unauthorizedExtension = The file you sent has an unauthorized extension ({0}). Allowed extensions for this upload are {1}
fileupload.download.nofile = No file was found with id {0}. Please check your link.
fileupload.download.filenotfound = The requested file ({0}) was not found in our system.

Change Log

1.2.1

  • Now UFile implements Serializable

1.2

  • fileuploader:form tag have now an id attribute for when you return, return an id and persist the ufile in our domain.
  • On the controller in the process method now return the id,
    params:[ufileId:ufile.id, id:params.id]
  • Added new show method in the controller to show the image
  • On the service now it has new methos to delete the file manually :
    def boolean deleteFile(def idUfile

1.1

  • File is now deleted from disk when respective domain class is deleted
  • New taglib method "prettysize"
  • After upload, FileUploaderController sends the uploaded file id in params.

1.0

  • Multiple file upload configuration
  • Taglib to build the multipart form
  • Extension-based restriction (per configuration)
  • Max permitted file size (per configuration)
  • i18n error messages
  • Download Action (with counter)
  • Taglib to create download link

TODO

  • pt-br i18n messages translation
  • i18n messages per upload group
  • format size of files (after prettysize) better
  • ENV specific configuration
  • Detailed Docs
  • Views and service
  • Log all downloads (ip, date)