使用JavaScript / jQuery下载文件的进度条

时间:2015-04-17 09:05:19

标签: javascript jquery jquery-ui progress-bar

我创建了一个页面,使用JSZip插件将多个文件作为单个zip文件下载。下载文件时,浏览器似乎被挂起,所以我想显示一个进度条,显示下载文件的进度。我是JavaScript和jQuery的新手,所以我无法使用各种网站上的代码。以下是我希望在我的代码中使用的links之一。

我想根据文件数量显示进度。我为每个循环都有一个迭代每个文件。请帮我使用上面链接中的代码。非常感谢提前。

这是我写的代码:

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';
            }
        });

2 个答案:

答案 0 :(得分:0)

你不能,这取决于浏览器用户界面,而不是HTML / DOM界面,请参阅评论Can I use jQuery UI Progress Bar to indicate the progress of downloading a file?

答案 1 :(得分:0)

如果sforce来自Salesforce AJAX Toolkit,那么您需要使用async methods

我强烈怀疑同步方法是否同步ajax请求:浏览器UI将冻结,直到每个请求完成并且zip结果准备就绪。即使您使用进度条,更新也不会显示UI是否被冻结。

使用异步请求,浏览器不再冻结:它将能够显示进度条更新。

在下面的代码中,fetchDataFromSForcessforce调用转换为jQuery Deferred(您需要jQuery UI,因此我假设您的页面上有jQuery)。手动合并异步回调可能导致丑陋的代码,而Deferred做得很好。我没有复制/粘贴生成fileIdList的块来保持这个答案可读,不要忘记把它放回去。

如果没有Salesforce服务器,我无法测试此代码,因此可能存在一些拼写错误,小错误等。

/**
 * 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';
    });
});