【发布时间】:2013-01-26 18:58:48
【问题描述】:
我一直在不懈地搜索,但就是无法弄清楚这一点。为什么此 XHR 连接在 Firefox 中可以正常工作,但在 Chrome 中会中断?顺便说一句,我将它与 AngularJS 结合使用。
$scope.upload = function(project, file) {
var formData = new FormData(); //Not really sure why we have to use FormData(). Oh yeah, browsers suck.
formData.append('', file.file); //The real file object is stored in this file container
file.xhr = new XMLHttpRequest();
file.xhr.open('PUT', '/api/projects/'+project._id+'/files', true);
//Progress event listener
file.xhr.upload.onprogress = function(event) {
if(event.lengthComputable) {
file.uploadPercent = Math.round(event.loaded / event.total * 100);
}
};
//Upload complete listener
file.xhr.upload.onload = function(event) {
file.uploaded = true;
};
//Every time the status changes
file.xhr.onreadystatechange = function(event) {
if(event.target.readyState == 4) {
//The file has been added, so tag the ID onto the file object
console.log(event.target.responseText);
file._id = JSON.parse(event.target.responseText)._id;
} else {
return;
}
};
file.xhr.send(formData);
};
在 Firefox 中,文件被发送到我的服务器,responseText 完全符合我的预期。但是,在 Chrome 中,我收到此错误:Error: INVALID_STATE_ERR: DOM Exception 11
Error: An attempt was made to use an object that is not, or is no longer, usable.,如果它准确地告诉我尝试使用哪个对象,这将更有帮助。我读过here,我应该尝试将async 设置为false 并使用onreadystatechange,但我不确定这有什么帮助,因为我已经在使用onreadystatechange。
【问题讨论】:
-
(ಠ_ಠ) 我在我的问题中引用了该帖子,特别是 Dave Lampert 的回答。当我在
xhr.open()调用中将async设置为 false 时,错误消失了,但 Chrome 仍然没有将文件发送到服务器。 -
如果您创建了fiddle,我很乐意看看。这是my upload service 的简化版本。也许这有帮助:)