skip to Main Content

I am uploading the multiple files through ajax, where i need to keep a progress bar. I am able to get the progress complete status only after all the process done, so i need to keep the progress bar showing status during upload.

Here when I clicking the ‘btnEditImageSave’ button, I am checking whether the existing file is getting delete and uploading in if condition.
In that storing the uploading file and passing it for uploading process in ajax complete function. In it that i have included the progress bar code to show the progress status, but its showing only after the all the process completes.

$('#btnEditImageSave').unbind().click(function (event) {
        $('#progressBardiv').css('width', '0');
        $('.progressBardiv').text('');  
 if (uploadedfiles.length > 0 && deleteFiles.length == 0) {
                if (editStoredFiles.length > 0) {
                    var files = new FormData();
                    for (var i = 0; i < editStoredFiles.length; i++) {
                        if (editStoredFiles[i].size > 0) {
                            files.append(editStoredFiles[i].name, editStoredFiles[i]);
                        }
                    }
                    uploadedfiles = [];
                    files.append('SerialNumber', editSerialNumber);
                  $.ajax({
                        type: "POST",
                        url: productionBaseUrl + '/Home/UploadDockingStationFiles',
                        data: files,
                        contentType: false,
                        processData: false,
                      async: true,

                      complete: function () {
                          uploadedfiles = [];
                          $('#editfileupload').val();
                          $.ajax({
                                type: "POST",
                                url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                data: JSON.stringify({
                                    SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
                                    FileSpinTimer: $('#txtEditTimer').val(),
                                    IsHDMIUpdate: isHDMIUpdate
                                }),
                               /*----My Progress Bar code----*/
                                xhr: function () {
                                    var xhr = new window.XMLHttpRequest();
                                    xhr.upload.addEventListener("progress", function (event) {
                                        if (event.lengthComputable) {
                                            var percentComplete = event.loaded / event.total;
                                            percentComplete = parseInt(percentComplete * 100);
                                            $('#progressBardiv').text(percentComplete + '%');
                                            $('#progressBardiv').css('width', percentComplete + '%');
                                        }
                                    }, false);
                                    return xhr;
                                },
                                complete: function () {
                                    $('#loading-popup').hide();
                                    $('#divEditDockingStationImages').dialog("close");
                                    $.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
                                    return false;
                                }
                            });
                        }
                    });
                }
            }
            else {
                $('#loading-popup').hide();
                $.popup('<pre>Message</pre>', "Please Select a File.", 'OK');
                return false;
            }
}


    <div class="progress">
     <div id="progressBardiv" class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="">
     <span class="sr-only"></span>
     </div>
     </div>

3

Answers


  1. Chosen as BEST ANSWER
     if (deleteFiles.length > 0 && uploadedfiles.length > 0) {
                $.ajax({
                    type: "POST",
                    url: productionBaseUrl + "/Home/DeleteDockingStationFiles",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    data: JSON.stringify({
                        serialNumber: editSerialNumber,
                        files: deleteFiles
                    }),
    
                    complete: function () {
                        deleteFiles = [];
                        if (editStoredFiles.length > 0) {
                            var files = new FormData();
                            for (var i = 0; i < editStoredFiles.length; i++) {
                                if (editStoredFiles[i].size > 0) {
                                    files.append(editStoredFiles[i].name, editStoredFiles[i]);
                                }
                            }
                            uploadedfiles = [];
                            files.append('SerialNumber', editSerialNumber);
                             $.ajax({
                                type: "POST",
                                url: productionBaseUrl + '/Home/UploadDockingStationFiles',
                                data: files,
                                contentType: false,
                                processData: false,
                                 async: true,
                                 xhr: function (data) {
                                     var xhr = new window.XMLHttpRequest(data);
                                     xhr.upload.addEventListener("progress", function (event) {
                                         if (event.lengthComputable) {
                                             var percentComplete = event.loaded / event.total;
                                             percentComplete = parseInt(percentComplete * 100);
                                             $('#progressBardiv').text(percentComplete + '%');
                                             $('#progressBardiv').css('width', percentComplete + '%');
                                         }
                                     }, false);
                                     return xhr;
                                 },
                                 beforeSend: function () {
                                    uploadedfiles = [];
                                     $('#editfileupload').val();
    
                                   $.ajax({
                                        type: "POST",
                                        url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
                                        contentType: "application/json; charset=utf-8",
                                        dataType: "json",
                                        data: JSON.stringify({
                                            SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
                                            FileSpinTimer: $('#txtEditTimer').val(),
                                            IsHDMIUpdate: isHDMIUpdate
                                        }),
    
                                       complete: function () {
                                            $('#loading-popup').hide();
                                            $('#divEditDockingStationImages').dialog("close");
                                            $.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
                                            return false;
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
    
    
            }
    

  2. You can use plUpload plugin to upload files..

    Follow this link:https://www.plupload.com/docs
    it has its own event for progressbar…

    See the sample code below…

    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: 'pickfiles', // you can pass in id...
        container: document.getElementById('container'), // ... or DOM Element itself
        url: "//",
        filters: {
            max_file_size: '500mb',
            mime_types: [
            { title: "PDF files", extensions: "pdf" }
            ]
        },
        flash_swf_url: '/plupload/js/Moxie.swf',    // Flash settings
        silverlight_xap_url: '/plupload/js/Moxie.xap',    // Silverlight settings
        init: {
            PostInit: function () {
            // whereas filelist is the divid which contains uploaded file names....
                document.getElementById('filelist').innerHTML = '';
    
                    uploader.start();
    
            },
            FilesAdded: function (up, files) {
                plupload.each(files, function (file) {
                    document.getElementById('filelist').innerHTML +=
                        '<div id ="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) +
                        ') <b></b> <a href ="" class="remove text-danger pull-right">Remove</a></div>' +
                        '<div class="progressbar" id ="progressBar_' + file.id + '"> <div class="mybar" id="myBar' + file.id + '"></div></div>';
                });
    
            },
            UploadProgress: function (up, file) {
                var $progressId = $("#filelist div#progressBar_" + file.id + " div.mybar");
                $progressId.css('width', file.percent + '%');
                //To Remove 'Remove Link' while file is in uploading state.
                $("#filelist div#" + file.id).find('a.remove').remove();
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            },
            FileUploaded: function (up, file, ServerResponse) {
                var response = JSON.parse(ServerResponse.response);
    
            },
            UploadComplete: function (up, file) {
                     },
            Error: function (up, err) {
                document.getElementById('console').innerHTML += "nError #" + err.code + ": " + err.message;
            }
        }
    });
    uploader.init();
    

    I have used in my project have a look on snapshot below,

    enter image description here

    Login or Signup to reply.
  3. For those in 2022 still looking how to measure an XHR upload operation progress, there’s an API called ProgressEvent (https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent) with broad support of major browsers. No need to use custom plugins.

    Also, a detailed post with examples on how to use this can be found here: https://medium.com/swlh/uploading-files-with-progress-monitoring-in-vanillajs-angular-and-vuejs-625e2491821

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search