angularjs - Access raw XHR object using $http -
i need access raw xmlhttprequest
object add file upload progress callback on browsers support it. possible, or have construct raw request myself? if so, how wrap raw xmlhttprequest
in promise object?
i simulated $http
call constructing custom xmlhttprequest
so:
uploadfile(file, progresshandler) { var xhr = new xmlhttprequest(), deferred = $q.defer(); xhr.open("post", "your/path", true); // method, url, async xhr.setrequestheader("content-type", file.type || "application/octet-stream"); xhr.onreadystatechange = function (e) { if (xhr.readystate == 4) { $rootscope.$apply(function () { // construct response object similar regular $http call // // data – {string|object} – response body transformed transform functions. // status – {number} – http status code of response. // headers – {function([headername])} – header getter function. // config – {object} – configuration object used generate request. var r = { data: xhr.response, status: xhr.status, headers: xhr.getresponseheader, config: {} }; if (r.status == 200) { deferred.resolve(r); } else { deferred.reject(r); } }); } }; if (progresshandler && xhr.upload) { xhr.upload.addeventlistener('progress', function(e) { progresshandler((e.loaded / e.total), e); }, false); } // available in xhr2, provide multipart fallback // if necessary xhr.send(file); return deferred.promise; }
Comments
Post a Comment