Friday, April 20, 2007

Easy fileupload with Grails

Uploading files in Grails is as simple as this. Add a upload closure in
the controller, then create the multipart form in the gsp.

def uploadFile = {
println "Getting new file"
def f = request.getFile('upfile')
if(!f.empty) {
f.transferTo( new File('someotherloc') )
println f
}
else {
flash.message = 'file cannot be empty'
redirect(action:'upload')
}
println "Done getting new file"
}

2 comments:

Gabriel said...

what about the save action?

does my gsp form have to have uplaod for the action?

What if I want to run the upload and save action at the same time?

Jonathan said...

Gabriel, the gsp code for this must be the next one:

<g:form method="post" action="uploadFile"
enctype="multipart/form-data">
<input type="file" name="upfile"/>
<input type="submit"/>
</g:form>

Remember that this gsp code must be in view/controllerName/ and its name must be nameAction.gsp

Here's the page where this blogger took the example, and so do i: Grails File Upload

To run upload and save action at the same time you can redirect. Add redirect(action:'save') at the end of your upload action.
Hope this help