April 9, 2020
Estimated Post Reading Time ~

Uploading a file using only Ajax

We often need to upload a file without a refreshing page or even before the 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 an HTML form that will allow the user to select the file that they wish to upload. Let's create a form with a file type in it
In grails, we prefer to use g:form tag
1
2
3
4
5
6
7
8
9
<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:
1
2
3
4
5
6
7
8
9
<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 let's 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.
1
2
3
4
5
6
7
8
<script type="text/javascript">
   $('form').ajaxSubmit({
        async: true,
        url: myCustomUrl,
        success : function(){
           ..... // Add your success handler code here
        }
</script>
I also created a demo app, showing this behavior. Feel free to check it out.
Source: https://www.tothenew.com/blog/uploading-a-file-using-only-ajax/


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.