javascript - ajax多文件上传显示进度怎么正确显示
PHP中文网
PHP中文网 2017-04-11 11:36:04
0
1
607

先是根据上传的文件数创建了显示进度的p

var upsongindex = 0;
var fileControl = document.getElementById("songListInputs");
    
    var files = fileControl.files;
    for (var i = 0; i < files.length; i++) {
        var curFile = files[i];
        var fname = curFile['name'].substring(curFile['name'].lastIndexOf("\\") + 1);
        //显示上传进度
        var list = document.getElementById(e);
        var node = "<p class='upSongItem'>" +
                    "<p id='upno'>" + (upsongindex + 1) + "</p>" +
                    "<p class='upSongIf' id='upsi1_" + upsongindex + "'>" + displayName + "</p>" +
                    "<p class='upSongIf' id='upsi2_" + upsongindex + "'>" + "上传中" + "</p>" +
                    "<p class='upSongIf' id='upsi3_" + upsongindex + "'>" + 0 + "%</p>" +
                    "<p class='upop'>" +
                    "<a href='#'><img src='img/edit.png' width='15' height='15' /></a>" +
                    "<a href='#'><img src='img/x.png' width='15' height='15' /></a>" +
                    "</p>"
        "</p>";
        list.innerHTML += node;
        uploadFiles(curFile);
        upsongindex++;

然后在这个函数里更新进度

function uploadFiles(curFile) {
    var progress = document.getElementById("upsi3_" + upsongindex);
    var loaded = document.getElementById("upsi2_" + upsongindex);

    var xhttp = new XMLHttpRequest();
    var oFormData = new FormData();
    oFormData.append('songList', curFile);
    xhttp.open('POST', 'uploadSong.ashx', true);
    xhttp.upload.onprogress = function (ev) {
        console.log(progress);
        var iScale = ev.loaded / ev.total;
        var percent = 100 * iScale;
        ////////////////////////////////////////这里
        progress.innerHTML = parseInt(percent) + "%";
    }
    //上传完成
    xhttp.onload = function () {
        progress.innerHTML = "";
        loaded.innerHTML = "已完成";
    }
    xhttp.send(oFormData);
}

不过在触发 xhttp.upload.onprogress事件的时候upsongindex的值已经是2了(假设上传3个文件)导致所有文件的上传进度都显示在最后一个p了,
请问怎么在xhttp.upload.onprogress事件处理函数里获得对应的upsongindex值,而不是最终的upsongindex值,谢谢

PHP中文网
PHP中文网

认证高级PHP讲师

membalas semua(1)
迷茫

upsongindex++;这句代码应该放到请求完成的回调方法中

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan