nin*_*nov 20 javascript ajax upload xmlhttprequest
我正在使用ajax上传文件.上传文件后,php应该检查它(哑剧,大小,病毒(clamscan)等) - 对于较大的文件,这需要几秒钟.当文件上传时,HTML5 <progress>正在填充,当文件准备好并且PHP开始检查时,进度应该切换到不确定.我认为对的方式来做到这一点(这两者都不能正常工作):
检查upload.onload事件
xhr.upload.addEventListener("load", function (e) {
    $("#uploadprogress").attr("value", false);
    $("#uploadprogress").attr("max", false);
    $("#progress").text("Checking file...");
});
这不起作用,因为onload-event在请求准备好时会激活,而不是在上传准备就绪时触发.
检查上传进度百分比= 100%
xhr.upload.addEventListener("progress", function (e) {
    if (e.lengthComputable && e) {
        p = (e.loaded / e.total);
        if (p==1) {
            $("#uploadprogress").attr("value", false);
            $("#uploadprogress").attr("max", false);
            $("#progress").text("Checking file...");
        } else {
            var percent = Math.ceil(p * 1000) / 10;
            $("#uploadprogress").val(e.loaded);
            $("#uploadprogress").attr("max", e.total);
            $("#progress").text("Uploading... " + percent + "%");
        }
   }
}
});
这不起作用,因为上传百分比有时会停止在大约.97%,尽管上传完成,PHP开始处理文件
检查这个还有其他可能吗?
zer*_*osh 52
您要侦听的事件readystatechange位于XHR对象上(而不是XHR.upload上).readyState是4上传完成后, 服务器关闭连接.loadend/ load无论服务器是否关闭连接,上传完成时都会触发.仅供参考,以下是您可以收听的事件以及何时触发的事件:
    var xhr = new XMLHttpRequest();
    // ...
    // do stuff with xhr
    // ...
    xhr.upload.addEventListener('loadstart', function(e) {
      // When the request starts.
    });
    xhr.upload.addEventListener('progress', function(e) {
      // While sending and loading data.
    });
    xhr.upload.addEventListener('load', function(e) {
      // When the request has *successfully* completed.
      // Even if the server hasn't responded that it finished.
    });
    xhr.upload.addEventListener('loadend', function(e) {
      // When the request has completed (either in success or failure).
      // Just like 'load', even if the server hasn't 
      // responded that it finished processing the request.
    });
    xhr.upload.addEventListener('error', function(e) {
      // When the request has failed.
    });
    xhr.upload.addEventListener('abort', function(e) {
      // When the request has been aborted. 
      // For instance, by invoking the abort() method.
    });
    xhr.upload.addEventListener('timeout', function(e) {
      // When the author specified timeout has passed 
      // before the request could complete.
    });
    // notice that the event handler is on xhr and not xhr.upload
    xhr.addEventListener('readystatechange', function(e) {
      if( this.readyState === 4 ) {
        // the transfer has completed and the server closed the connection.
      }
    });
| 归档时间: | 
 | 
| 查看次数: | 16012 次 | 
| 最近记录: |