我一直在不懈地寻找,但就是无法弄清楚这个问题。为什么此 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
错误:尝试使用一个不可用或不再可用的对象。
,如果它准确地告诉我尝试使用哪个对象,将会更有帮助。我读过here我应该尝试将 async
设置为 false 并使用 onreadystatechange
,但我不确定这有什么帮助,因为我已经在使用 onreadystatechange
>.
最佳答案
2009 年的错误:提交表单时 XMLHttpRequest 不起作用 - https://bugs.webkit.org/show_bug.cgi?id=23933
关于javascript - Chrome/WebKit XHR 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540418/