Grails - File Upload

Uploading a file

The following is a simple example of a file upload in Grails. This example was built and tested with Grails 1.0.2.

Create the form in the view

In your GSP page, add the following code for creating a form for uploading the file.

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

Handle the upload in the controller

Create the controller with: grails create-controller YourControllerName

Here is a controller action that prints the entire text file to the console. The request object is automatically a Spring MultipartHttpServletRequest when dealing with a multipart HTTP request. Then add the code to grails-app/controllers/YourControllerNameController.groovy

def save = {
    println request.getFile("file").inputStream.text
}

You should also create a file: grails-app/views/yourControllerName/save.gsp for the action.

To transfer the file to your local drive

def downloadedfile = request.getFile('file');
downloadedfile.transferTo(new File('c:/somefolder/filename.jpeg'))