7.1.8 Uploading Files - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.0.11
7.1.8 Uploading Files
Programmatic File Uploads
Grails supports file uploads using Spring's MultipartHttpServletRequest interface. The first step for file uploading is to create a multipart form like this:Upload Form: <br /> <g:uploadForm action="upload"> <input type="file" name="myFile" /> <input type="submit" /> </g:uploadForm>
uploadForm
tag conveniently adds the enctype="multipart/form-data"
attribute to the standard <g:form>
tag.There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance directly:def upload() { def f = request.getFile('myFile') if (f.empty) { flash.message = 'file cannot be empty' render(view: 'uploadForm') return } f.transferTo(new File('/some/local/dir/myfile.txt')) response.sendError(200, 'Done') }
InputStream
and so on with the MultipartFile interface.File Uploads through Data Binding
File uploads can also be performed using data binding. Consider thisImage
domain class:class Image { byte[] myFile static constraints = { // Limit upload file size to 2MB myFile maxSize: 1024 * 1024 * 2 } }
params
object in the constructor as in the example below, Grails will automatically bind the file's contents as a byte
to the myFile
property:def img = new Image(params)
byte
properties.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
}