Grails - Controllers - File Uploads

Handling File Uploads

To upload a file the first step is to create a multipart form like the one below:

Upload Form: <br />
		<g:form action="upload" method="post" enctype="multipart/form-data">
			<input type="file" name="myFile" />
			<input type="submit" />
		</g:form>


There are then a number of ways to handle the file upload. The first way is to work with the Spring MultipartFile instance directly:

def upload = {
    def f = request.getFile('myFile')
    if(!f.empty) {
      f.transferTo( new File('someotherloc') )
      response.sendError(200,'Done');
    }    
    else {
       flash.message = 'file cannot be empty'
       redirect(action:'uploadForm')
    }
}


This is clearly handy for doing transfers to other destinations and manipulating the file directly (you can also open an InputStream, see javadoc). The next way to deal with file uploads is to bind the file's contents to a domain class or command bean. Lets look at a domain class example say you have an 'Image' domain class like the below:

class Image {
   byte[] myFile
}


Now when we do the usual set of properties like the below:
But what file does like the below go in????
def img = new Image()
img.properties = params


The contents of the file will automatically be converted into a byte[] and set on the image domain class. It is also possible to set the contents of the file as a string by changing the type of the 'myFile' property on the image to a String type:

class Image {
   String myFile
}


The final way to do this is via the 'bindData' method which you can use in combination with a command object. Say we have a command object like the below:

class UploadCommand {
   byte[] myFile
}


We can then use it in the controller like this:

def upload = {
   def uc = new UploadCommand()
   bindData(uc, params)
   assert uc.myFile != null
}