Django Ajax file-uploader with bootstrap progressbar

Hey guys. You might have implemented the file upload logic in your web-app. Usually in Google chrome it shows the file upload percentage, but in other browsers it doesn’t show. What if you are using some other browser and you have uploaded a large file of size 10-20MB approx and  it takes 5 minutes to upload. The user will doubt the system is uploading the file or not and that can not be fixed with code also, because that depends on lot of file transfer parameters. Here is a fix to that problem. user can show the file upload percentage in the front end. But that is not possible in http request. We have to use ajax to do that.

You can use django-ajax form submission with jquery to implement ajax up-loader for you app. to know how to do that click here.

Now suppose we have configured the ajax up-loader to upload our file. But ajax will do the task on click but it will not show any changes on front-end and our goal is to show the progress bar with file upload percentage.

For that

just add the following parameters in the $.ajax as a parameter.

cache: true,
dataType: 'json',
processData: false,
contentType: false,
xhr: function()
{
    $('.progress').css("display",'block');
    $('#percent').text('0%');
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(e){
    if (e.lengthComputable) {
        var percentComplete = e.loaded / e.total;
        //Do something with upload progress
        console.log(percentComplete)
        $('.bar').css ('width', (percentComplete)*100+'%');
        $('#percent').text(Math.floor((percentComplete)*100)+'%');
    }
}, false);
return xhr;
},

Just add a new div in the html for showing the progreebar like the following.

<div class="progress progress-striped active" >
    <div class="bar" style="width: 0%;"><span id="percent"></span></div>
</div>

And there you go Upload a file and it will show you the progress of upload in a pretty clean bootstrap progress-bar.

My Reference:

http://stackoverflow.com/questions/20750106/loading-bar-based-on-ajax-call

Advertisements

One thought on “Django Ajax file-uploader with bootstrap progressbar

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s