How to implement Progress Bar and Callbacks with async nature of the FileReader

徘徊边缘 提交于 2019-12-04 02:21:40

Let's address your second problem first. You need to define your after-completion code in a separate function, and call that function once all the files have uploaded:

function() {
    var total = Files.length; loaded = 0;
    for (var i in Files) {
        var fileReader = new FileReader();
        fileReader.readAsBinaryString(Files[i]);
        fileReader.onload = function() {

            // do something on FileReader onload
            loaded++;

            if (loaded == total){
                onAllFilesLoaded();
            }
        }

        fileReader.onprogress = function(data) {
            if (data.lengthComputable) {                                            
                var progress = parseInt( ((data.loaded / data.total) * 100), 10 );
                console.log(progress);
            }
        }
    }
}

function onAllFilesLoaded(){
    //do stuff with files
}

Now, for tracking progress, there are a couple different ways you could address that. Right now you are loading all the files at once, and each file is reporting its own progress. If you don't mind less frequent progress updates, you could simply use the onload handler to report progress each time a file has uploaded. If you want really fine-grained, accurate progress updates, you are going to have to calculate the total size of all the files combined, then keep track of how much of each file has loaded, and use the sum of what has loaded for each file compared to the total size of all files to report progress.

Alternatively, assuming that you are implementing this with a progress bar rather than console.log, you could provide a separate progress bar for each file that's being uploaded, and calculate progress for each file exactly as you're doing it now, then updating the corresponding progress bar. Let me know if any of that needs clarification.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!