Javascript – Progress Bar for downloading files using JavaScript/jQuery

javascriptjqueryjquery-uiprogress-bar

I have created a page to download multiple files as a single zip file using JSZip plugin. While downloading the files the browser seems to be hanged so I want to show a progress bar that shows the progress of downloading the files. I am new to JavaScript and jQuery so I am unable to use the code found on various sites. Here is one of the links that I would prefer to use in my code.

I would like to show the progress on the basis of number of files. I am having one for each loop which iterates on each file. Please help me to use the code in the above link. Many thanks in advance.

Here is the code I have written:

document.getElementById("downloadZip").addEventListener("click", function ()
        {
            sforce.connection.sessionId = '{!$Api.Session_ID}';
            var docList = JSON.parse('{!docList}');
            var checkedRecords = [];
            for(var key in docList)
            {
                if(docList.hasOwnProperty(key))
                {
                    var isSelected = document.getElementById(docList[key].docRecordId).firstChild.checked;
                    if(isSelected)
                    {
                        checkedRecords.push(docList[key]);
                    }
                }
            }
            console.log(checkedRecords);
            if(checkedRecords.length > 0)
            {
                document.getElementById("errorMessage").innerHTML = '';
                var fileIdList = [];
                for(var key in checkedRecords)
                {
                    if(checkedRecords.hasOwnProperty(key))
                    {
                        var currentFile = checkedRecords[key];
                        var fileIdMap = checkedRecords[key].docFileMap;
                        var fileId;
                        for(var j in fileIdMap)
                        {
                            fileId = fileIdMap[j];
                        }
                        fileIdList.push(fileId);
                    }
                }
                var zip = new JSZip();
                var content = null;

                for(var key in fileIdList)
                {
                    if(fileIdList.hasOwnProperty(key))
                    {
                        var query = "Select Id,Title,Description,ContentUrl,ContentDocumentId,VersionData,PathOnClient,FileType From ContentVersion WHERE Id = '" + fileIdList[key] + "'";
                        try
                        {
                            var result = sforce.connection.query(query);
                            var records = result.getArray("records");
                            var filename = records[0].PathOnClient;
                            var packCount = 1;
                            if(filename === '')
                            {
                                filename = 'ContentPack_'+packCount;
                                packCount++;
                            }
                            zip.file(filename, records[0].VersionData,{base64: true});
                        }
                        catch(err)
                        {
                            document.getElementById("errorMessage").innerHTML = 'Content Not Found - ' + err.message;
                            document.getElementById("errorMessage").style.color = 'red';
                        }
                    }
                }
                content = zip.generate({type: "blob"});
                saveAs(content, "myZip.zip");
                var sentTo = document.getElementById("ChooseSentTo").value;
                updateDocumentation(checkedRecords,sentTo);
            }
            else
            {
                document.getElementById("errorMessage").innerHTML = 'Please select a record';
                document.getElementById("errorMessage").style.color = 'red';
            }
        });

Best Answer

If sforce is from the Salesforce AJAX Toolkit then you will need to use the async methods.

I strongly suspect the synchronous methods to do sync ajax requests : the browser UI will freeze until every requests complete and the zip result is ready. Even if you use a progress bar, the updates won't show if the UI is frozen.

With async requests, the browser won't freeze anymore : it will be able to display the progress bar updates.

In the code below, fetchDataFromSForces transforms a sforce call to a jQuery Deferred (you want jQuery UI so I assumed that you have jQuery on your page). Manually merging async callback can lead to an ugly code and Deferred does that nicely. I didn't copy/paste the block that generate fileIdList to keep this answer readable, don't forget to put it back.

Without a Salesforce server I can't test this code so there may be some typos, small bugs, etc.

/**
 * Fetch data from the server asynchronously and add files in the zip.
 * @param {String} id the id of the ContentVersion to fetch.
 * @param {JSZip} zip the zip file to fill in.
 * @param {SForce} sforce the Sales Force object.
 * @return {jQuery.Deferred} the deferred containing the result.
 */
function fetchDataFromSForces(id, zip, sforce) {
    var deferred = jQuery.Deferred();
    var query = "Select Id,Title,Description,ContentUrl,ContentDocumentId,VersionData,PathOnClient,FileType From ContentVersion WHERE Id = '" + id + "'";
    sforce.connection.query(query, {
        onSuccess : function (result) {
            var currentProgress = $(".your-progressbar").progressbar("option", "value") || 0;
            currentProgress++;

            // put the result in the zip
            var records = result.getArray("records");
            var filename = records[0].PathOnClient;
            if(filename === '') {
                filename = 'ContentPack_'+currentProgress;
            }
            zip.file(filename, records[0].VersionData,{base64: true});

            // update the progress bar
            $(".your-progressbar").progressbar("option", "value", currentProgress);

            deferred.resolve(zip);
        },
        onFailure : function (error) {
            deferred.reject(error);
        }
    });
    return deferred;
}

// Create your progress bar first.
$(".your-progressbar").progressbar();

document.getElementById("downloadZip").addEventListener("click", function () {

    // ...
    // Here, the previous code here to init sforce and get fileIdList
    // ...

    var zip = new JSZip();
    var deferreds = [];

    for(var key in fileIdList) {
        if(fileIdList.hasOwnProperty(key)) {
            deferreds.push(fetchDataFromSForces(fileIdList[key], zip, sforce));
        }
    }
    // re-init the progress bar
    $(".your-progressbar").progressbar("option", "value", 0);
    $(".your-progressbar").progressbar("option", "max", fileIdList.length);
    // join all deferreds into one
    $.when.apply($, deferreds).done(function () {
        var content = zip.generate({type: "blob"});
        saveAs(content, "myZip.zip");
        var sentTo = document.getElementById("ChooseSentTo").value;
        updateDocumentation(checkedRecords,sentTo);
    }).fail(function (err) {
        document.getElementById("errorMessage").innerHTML = err.message;
        document.getElementById("errorMessage").style.color = 'red';
    });
});