Category Covered

Groovy and grails file upload

In your view file use the following form to upload files on grails

<g:uploadForm action="saveFile" method="post" >
    <table style="margin: auto; border-top: none!important; margin-bottom: 20px;">
        <tr>
            <td>&nbsp;</td>
            <td valign="top" class="name">
                <label for="payload">File:</label>
            </td>
            <td valign="top">
                <input type="file" id="payload" name="payload"/>
            </td>
            <td valign="top">
                <input type="submit" />
            </td>
            <td>&nbsp;</td>
        </tr>
    </table>
</g:uploadForm>


Then make a function where the form will submit and upload the file on a folder on grails

def saveFile() {
    def webRootDir = servletContext.getRealPath("/")
     def uploadedFile = request.getFile('payload')
    /*You can get some important file information on grail like file name, file size etc*?
    /*println "Class: ${uploadedFile.class}"
     println "Name: ${uploadedFile.name}"
     println "OriginalFileName:          ${uploadedFile.originalFilename}"
     println "Size: ${uploadedFile.size}"
     println "ContentType: ${uploadedFile.contentType}"*/
   
    /*File upload code on grails*/
    def userDir = new File(webRootDir, "/mt940/")
     userDir.mkdirs()
     uploadedFile.transferTo( new File( userDir, uploadedFile.originalFilename))

}