HTML5 file uploading with multiple progress bars

前端 未结 2 1799
孤城傲影
孤城傲影 2020-12-25 08:49

I\'m uploading multiple files via XmlHTTPRequest and HTML5. I have the uploading working fine, but I would like to have a progress bar for each file upload going on. The c

相关标签:
2条回答
  • 2020-12-25 09:10

    I think I found a solution for this problem. It looks working on some of my tests. I'm not very good at english thus I'll just share my sample script. If you ask any question, I'll try to explain more :)

    // This is input object which type of file.  
    var uploader = document.getElementById("fileUploader"); 
    
    // We'll send a new post for each file.
    for(var i=0, j=uploader.files.length; i<j; i++)
    {
        var uploaderForm = new FormData(); // Create new FormData
        uploaderForm.append("action","upload"); // append extra parameters if you wish.
        uploaderForm.append("up_file",uploader.files[i]); // append the next file for upload
    
        var xhr = new XMLHttpRequest();
    
        xhr.addEventListener("loadstart", function(e){
            // generate unique id for progress bars. This is important because we'll use it on progress event for modifications
            this.progressId = "progress_" + Math.floor((Math.random() * 100000)); 
    
            // append progress elements to somewhere you want
            $("body").append('<div id="' + this.progressId + '" class="myCustomProgressBar" ></div>');
        });
        xhr.addEventListener("progress", function(e){
            var total = e.total;
            var loaded = e.loaded;
            var percent = (100 / total) * loaded; // Calculate percentage of loaded data
    
            // I animate progress object. Notice that i use "this.progressId" which i created on loadstart event.
            $("#" + this.progressId).animate({"width":300 * (percent / 100)}, 800);
        });
    
        xhr.open("POST","index.php");
        xhr.send(uploaderForm);
    }
    
    0 讨论(0)
  • 2020-12-25 09:21

    Your example doesn't work properly becourse you don't take into account that xhr progress event is fired when all list items had been already created. However there are a lot of ways to make your example work. The idea is to let xhr know what exactly list item it is dealing with. For example use this code (I didn't check if it works. The purpose of this code is to describe the idea):

    var xhr = new XMLHttpRequest();
    xhr.upload.li = li;
    xhr.upload.addEventListener('progress', function(e) {
        var percent = parseInt(e.loaded / e.total * 100);
        this.li.find(".progressbar").width(percent);
    }, false);
    
    0 讨论(0)
提交回复
热议问题