javascript - Chrome/WebKit XHR 文件上传

标签 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 错误:尝试使用一个不可用或不再可用的对象。,如果它准确地告诉我尝试使用哪个对象,将会更有帮助。我读过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/

相关文章:

javascript - 从 JS 到 Drupal 的 URL 编码字符串

javascript - AngularJS 如果复选框是选中显示

javascript - 单独文件中的 thinky 模型 : how to handle cyclical/circular dependencies

java - HttpURLConnection 不响应也不抛出异常

php - XmlHttpRequest 状态 = 远程服务器上的 0,本地主机上的状态 200

javascript - 使用 formData() 上传多个文件

javascript - 是否可以使用 XHR 上传文件目录?

php - 如何将 PHP 数组转码为 JSON 数组?

javascript - 为什么要重用 `undefined` ?

javascript - CORS POST 请求在普通 JavaScript 中工作,但为什么不使用 jQuery?