Chrome / WebKit XHR文件上传

时间:2013-01-26 18:58:49

标签: javascript xmlhttprequest

我无情地搜索过,但是无法想出这一点。为什么这个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,但我不确定这有何帮助,因为我已经在使用{{1} }。

1 个答案:

答案 0 :(得分:0)

2009年的错误:XMLHttpRequest在提交表单时无效 - https://bugs.webkit.org/show_bug.cgi?id=23933