PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How to get the file uploading progress status in ajax call?

 September 06, 2022     ajax, javascript, jquery, progress-bar     No comments   

Issue

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>

Solution

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



Answered By - Ishwar Gagare
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing