Uploading a file using only Ajax

04 / Jul / 2014 by Mansi Arora 1 comments

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

<g:form name="myForm">
      <label for="name">
   <input id="name" name="name" type="text"/>
  <input type="file" name="inputFile">

We can even use a normal form tag:

<form method="post" enctype="multipart/form-data">
        <label for="name">
        <input id="name" name="name" type="text"/>
   <input type="file" id="inputFile"  name="inputFile">

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.

<script type="text/javascript">
        async: true,
        url: myCustomUrl,
        success : function(){
           ..... // Add your success handler code here

I also created a demo app, showing this behaviour. Feel free to check it out.


Mansi Arora



comments (1 “Uploading a file using only Ajax”)

Leave a comment -