Step by step JQuery Ajax file upload with progress bar
Here in this article we will learn Step by step JQuery Ajax file upload with progress bar along with running demo.
now a days as websites are made advanced most of the things are being performed by ajax, file upload can also be performed via ajax as background process, not only that we can get continuous status of upload and show user how much file is uploaded by displaying a decent progress bar.
Before starting have a look at demo at this link JQuery-Ajax-file-upload-progressbar. we will be creating something like this.
Step for JQuery Ajax file upload with progress bar
We can submit our file and text data via ajax, how to handle things?
- write form submit event using JQuery and prevent default functionality as
12$('body').on('submit','#frm',function(e){e.preventDefault(); - Create FormData object as
1var data = new FormData();
- Assign it file as
1data.append('file', frm.find( '#txtFile' )[0].files[0]);
- We can assign other data too like
1data.append('title',frm.find('#txtTitle').val());
- Create httpRequest object as
1var ajax = new XMLHttpRequest();
- bind events to above object as below code
123456789101112ajax.upload.addEventListener('progress',function(evt){//we will get progress here and update progressbar},false);ajax.addEventListener('load',function(evt){//this event will be fired when upload completes},false);ajax.addEventListener('error',function(evt){//this event will be fired when some error occurs},false);ajax.addEventListener('abort',function(evt){//this event will be fired when file upload is aborted},false); - assign method and url to ajax object as
1ajax.open('POST',url);
- call send method of ajax object as
1ajax.send(data);
This is all, you just have to handle and code above 4 events as you need it. the following 2 snapshots displays how images out form will be looking during file uploading and the send one displays when file upload is completed.
to view running demo click this link jquery-ajax-file-upload-progressbar, if you want to download complete source code of this demo click this link Download source code customize and make changes according to your requirements and needs. let me know if you have any issues I will try my best to help you out.
Comments