简体   繁体   English

Chrome / WebKit XHR文件上传

[英]Chrome/WebKit XHR File Upload

I have searched relentlessly but just can't figure this one out. 我进行了不懈的搜索,但无法弄清楚这一点。 Why will this XHR connection work perfectly fine in Firefox but breaks in Chrome? 为什么此XHR连接在Firefox中可以很好地工作而在Chrome中却无法使用? I'm using this in conjunction with AngularJS, by the way. 顺便说一下,我将其与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);
            };

In Firefox, the file is sent just fine to my server, and the responseText is returned exactly like I'd expect. 在Firefox中,文件可以很好地发送到我的服务器,并且responseText返回的结果与我期望的完全相同。 However, in Chrome, I get this error: Error: INVALID_STATE_ERR: DOM Exception 11 Error: An attempt was made to use an object that is not, or is no longer, usable. 但是,在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. , which would be more helpful if it told me exactly what object was attempted to be used. ,如果它告诉我确切地尝试使用哪个对象,则将更有帮助。 I've read here that I should try to set async to false and use onreadystatechange , but I'm not sure how that helps, since I'm already using onreadystatechange . 我在这里读到我应该尝试将async设置为false并使用onreadystatechange ,但是我不确定这样做有什么帮助,因为我已经在使用onreadystatechange

自2009年以来的错误:提交表单时XMLHttpRequest不起作用-https://bugs.webkit.org/show_bug.cgi?id =23933

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM