AJAX的文件下载:progress事件,下载事件、文件、AJAX、progress

2023-09-10 20:41:34 作者:她都不难受

据我所知,xhr.upload.onprogress事件(文件上传)。 像这样的:

I understand the xhr.upload.onprogress event (file upload). Like this :

    xhr.upload.onprogress = function(e) {   // if (e.lengthComputable) ...
        var percentUploaded = Math.floor(100 * e.loaded / e.total);
        progressBarElem.value = percentUploaded;
        messageAreaElem.innerHTML = percentUploaded + "% uploaded";
    }

但对于xhr.onprogress事件,这是从服务器上下载文件?

But what about the xhr.onprogress event, which is file download from the server ?

我无法找到一个简单的例子。

I can't find a simple example of this.

帕特里克

推荐答案

作为文件说:

进度事件均存在下载和上传传输。下载事件打响了XMLHtt prequest对象本身,如在上面的示例。上传事件打响了XMLHtt prequest.upload对象。

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object.

您可以尝试使用下面的code,以验证

You can try to use following code to validate

var progress = 0.1;

var oReq = new XMLHttpRequest();

//Download progress
oReq.addEventListener("progress", function(evt){
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    //Do something with download progress
    console.log(evt.total);
    if(percentComplete > progress ){
        console.log("Finish " + progress * 100 + "%.");
        progress += 0.1;

    }
  }
}, false);

oReq.open("get", "url", true);
oReq.send();