We often need to upload a file without refreshing page or even before user submits the complete form.
The first thing we need is a HTML form that will allow the user to select the file that they wish to upload. Lets create a form with file type in it
In grails, we prefer to use g:form tag
<g:form name="myForm"> <div> <label for="name"> <strong>Name</strong> </label> <input id="name" name="name" type="text"/> </div> <input type="file" name="inputFile"> </g:form>
We can even use a normal form tag:
<form method="post" enctype="multipart/form-data"> <div> <label for="name"> <strong>Name</strong> </label> <input id="name" name="name" type="text"/> </div> <input type="file" id="inputFile" name="inputFile"> </form>
Now lets include jQuery form plugin which will provide us functionality to upload files using ajax
Now all we need to do is call ajaxSubmit method, which is provided by jQuery form plugin
I also created a demo app, showing this behaviour. Feel free to check it out.