Programmatic File Uploads

Grails supports file uploads via Spring's MultipartHttpServletRequest interface. 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('/some/local/dir/myfile.txt') )
      response.sendError(200,'Done');
    }    
    else {
       flash.message = 'file cannot be empty'
       render(view:'uploadForm')
    }
}

This is clearly handy for doing transfers to other destinations and manipulating the file directly as you can obtain an InputStream and so on via the MultipartFile interface.

File Uploads through Data Binding

File uploads can also be performed via data binding. For example say you have an Image domain class as per the below example:

class Image {
   byte[] myFile
}

Now if you create an image and pass in the params object such as the below example, Grails will automatically bind the file's contents as a byte to the myFile property:

def img = new Image(params)

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
}