我正在尝试使用XMLHttpRequest发送文件,虽然它能工作,但我的进度监视器却无法工作。我尝试上传了一个700KB和一个3MB的文件,但遇到了同样的问题:“progress”事件只触发一次,并且事件中的event.loaded和event.total总是相同的。上传需要适当的时间,但事件只触发一次。在Chrome和Firefox中测试时出现了相同的问题。以下是事件的控制台日志。
XMLHttpRequestProgressEvent {totalSize: 764277, position: 764277, total: 764277, loaded: 764277, lengthComputable: true…}
bubbles: false
cancelBubble: false
cancelable: true
clipboardData: undefined
currentTarget: XMLHttpRequestUpload
defaultPrevented: false
eventPhase: 0
lengthComputable: true
loaded: 764277
position: 764277
returnValue: true
srcElement: XMLHttpRequestUpload
target: XMLHttpRequestUpload
timeStamp: 1390945794935
total: 764277
totalSize: 764277
type: "progress"
__proto__: XMLHttpRequestProgressEvent
以下是我的JavaScript源代码
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
console.log(e);
}, false);
xhr.onload = function () {
if (xhr.status === 200) {
console.log('done');
}
else if (xhr.status == 403) {
console.log('forbidden');
}
else {
console.log('error');
}
};
xhr.open("POST", '/upload.php');
xhr.send(formData);