XHR 오브젝트의 "progress"이벤트를 사용하여 다운로드 진행 상황을 확인하고 싶습니다.XHR 진행 이벤트 리스너를 사용하도록 http 응답을 올바르게 작성하는 방법
는 여기에 내가 유사한 코드를 작성했습니다
var req = new XMLHttpRequest();
req.addEventListener("progress", updateProgress, false);
req.addEventListener("load", transferComplete, false);
req.addEventListener("error", transferFailed, false);
req.addEventListener("abort", transferCanceled, false);
req.open();
...
// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded/evt.total;
...
} else {
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
alert("The transfer is complete.");
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
MDN에서 예제 코드,하지만 progress 이벤트의 lengthComputable
필드가 거짓으로 밝혀졌습니다. loaded
필드는 일부 유한 값이지만 total
은 0으로 설정됩니다.
위의 코드 예에서 설명한 의견에서 볼 때 브라우저가 의미있는 다운로드 진행률을 계산하기에 충분한 HTTP 응답 정보를 얻지 못함을 알 수 있습니다.
이 작품을 작성하는 올바른 방법은 무엇입니까? 내 테스트에서 볼 수있는 응답은 Transfer-encoding: chunked
과 Content-Length: 8
입니다. 토네이도 웹 서버에서 생성하고 있습니다.
이 두 번째 트릭은 잘했다. – Jayesh
두 번째 트릭은 다소 효과가있었습니다. gzip 압축 때문에이 작업을 수행해야했습니다. gzip은 항상 lengthComputable을 false로 만들었습니다. Content-Length 헤더는 압축 된 크기에 적합하며 페이지를로드 할 수 있습니다. 나는 압축 수준을 대략적으로 맞추고 그에 따라 총계를 조정해야했다. 다행히도이 작업을 수행하는 더 좋은 방법이 있습니다. – Hobbes