Uploading a file using only Ajax
We often need to upload a file without refreshing page or even before user submits the complete form.
We have been using flash uploaders or i-frames to achieve that. However now it is possible to upload a file using only ajax and javascript.
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
[java]
<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>
[/java]
We can even use a normal form tag:
[java]
<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>
[/java]
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
with options.
[java]
<script type="text/javascript">
$(‘form’).ajaxSubmit({
async: true,
url: myCustomUrl,
success : function(){
….. // Add your success handler code here
}
</script>
[/java]
I also created a demo app, showing this behaviour. Feel free to check it out.
Cheers!
Mansi Arora
mansi[at]intelligrape[dot]com
Im obliged for the blog article.Much thanks again. Will read on…