1

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? I'm using this in conjunction with AngularJS, by the way.

$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. 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., 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.

Community
  • 1
  • 1
winduptoy
  • 5,366
  • 11
  • 49
  • 67
  • Did you read this, http://stackoverflow.com/questions/3488698/invalid-state-err-dom-exception-11-webkit ? – Salman Jan 26 '13 at 19:30
  • (ಠ_ಠ) I referenced that post in my question, specifically the answer by Dave Lampert. When I set `async` to false in my `xhr.open()` call, the error is gone but Chrome still doesn't even send the file to the server. – winduptoy Jan 26 '13 at 20:10
  • If you create a [fiddle](http://jsfiddle.net/) I'm happy to take a look. Here's a simplified version of [my upload service](http://jsfiddle.net/5CYDV/). Maybe that helps :) – John B. Feb 01 '13 at 13:24

1 Answers1

0

Bug from 2009: XMLHttpRequest doesn't work while submitting a form - https://bugs.webkit.org/show_bug.cgi?id=23933