1

I need a progress bar in my file uploader. This is the ajax call I am using for file upload and progress bar

$(function() {

        $('button[type=button]').click(function(e) {
            e.preventDefault();
            //Disable submit button
            $(this).prop('disabled',true);

            var form = document.forms[0];
            var formData = new FormData(form);

            // Ajax call for file uploaling
            var ajaxReq = $.ajax({
                url : URI.file.multipleFileUploadUrl(),
                type : 'POST',
                data : formData,
                cache : false,
                contentType : false,
                processData : false,
                xhr: function(){
                    //Get XmlHttpRequest object
                     var xhr = $.ajaxSettings.xhr() ;

                    //Set onprogress event handler

                     xhr.upload.onprogress = function(event){
                        var perc = Math.round((event.loaded / event.total) * 100);
                        $('#progressBar').text(perc + '%');
                        $('#progressBar').css('width',perc + '%');
                     };

                     return xhr ;
                },
                beforeSend: function( xhr ) {
                    //Reset alert message and progress bar
                    $('#alertMsg').text('');
                    $('#progressBar').text('');
                    $('#progressBar').css('width','0%');
                }
            });

            // Called on success of file upload
            ajaxReq.done(function(msg) {
                $('#alertMsg').text(msg);
                $('input[type=file]').val('');
                $('button[type=submit]').prop('disabled',false);
            });

            // Called on failure of file upload
            ajaxReq.fail(function(jqXHR) {
                $('#alertMsg').text(jqXHR.responseText+'('+jqXHR.status+
                        ' - '+jqXHR.statusText+')');
                $('button[type=submit]').prop('disabled',false);
            });
        });
    });

Find below is the file upload which works correctly without integrating the progress bar.

function multipleFileUpload(form) {
    var uploadSuccess = true;
    var data = new FormData(form);

    var csrf_headerName  = $("meta[name='_csrf_header']").attr("content");
    var csrf_paramValue  = $("meta[name='_csrf']").attr("content");
    ShowLoad();
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: URI.file.multipleFileUploadUrl(),
        data: data,
        beforeSend: function (request) {
            request.setRequestHeader(csrf_headerName, csrf_paramValue);
        },
         processData: false,
         contentType: false,
         cache: false,
         timeout: 6000000,
         success: function (data) {
            HideLoad();
            data.forEach(function(d, index){
                if(d.status === 'ERROR'){
                    // HideLoad();
                    uploadSuccess = false;
                    toastr.error('Error has occurred while uploading image file '+d.data.name);
                }else if( d.data.id != null ){
                    //HideLoad();
                    //toastr.success('Successfully updated '+d.data.name, 'Upload Success');
                }
            });

            if(uploadSuccess){
                mediaFileMetaDataSave(data[0],data[1]);
            }
         },
         error: function (e) {
            HideLoad();
            toastr.error('Error has occurred while uploading attachments.');
         }
    });
 }

WHen I use the above code in my script I can do file upload properly although the progress bar reach 100% immediately before file upload is complete. What is wrong here?

4
  • 1
    Well lets my get my mining hat, a pick axe and a torch and start digging through this code heap. Please update and show us where the exact problem is --> minimal reproducible example. Commented Oct 20, 2017 at 10:51
  • I just simplified the question. Please can you see it now? Commented Oct 20, 2017 at 10:56
  • Are you testing this locally, A file upload could be instantanously. Commented Oct 20, 2017 at 10:56
  • yes. I tested with a large file. And also I see progress changes immediately from 0 to 100% Commented Oct 20, 2017 at 10:57

1 Answer 1

4

This works fine.

function submitForm(form) {
        ShowLoad();
        var data = new FormData(form);
        var csrf_headerName  = $("meta[name='_csrf_header']").attr("content");
        var csrf_paramValue  = $("meta[name='_csrf']").attr("content");

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: URI.file.singleFileUploadUrl(),
        data: data,
        beforeSend: function (request, xhr) {
            request.setRequestHeader(csrf_headerName, csrf_paramValue);
             //Reset alert message and progress bar
            $('#alertMsg').text('');
            $('#progressBar').text('');
            $('#progressBar').css('width','0%');
        },
        processData: false,

        contentType: false,
        cache: false,
        timeout: 6000000,
        success: function (data) {
            HideLoad();
        },

        xhr: function(){
            //Get XmlHttpRequest object
             var xhr = $.ajaxSettings.xhr() ;
            //Set onprogress event handler
             xhr.upload.onprogress = function(data){
                var perc = Math.round((data.loaded / data.total) * 100);
                $('#progressBar').text(perc + '%');
                $('#progressBar').css('width',perc + '%');
             };
             return xhr ;
        },
        error: function (e) {
            HideLoad();
            toastr.error('Error has occurred while uploading the media file.');
        }
    });
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.