我需要访问原始
XMLHttpRequest对象,以在支持它的浏览器上添加文件上载进度回调.这是可能的,还是我必须自己构建原始请求?如果是这样,我如何在promise对象中包装原始XMLHttpRequest?
我模拟了构建自定义XMLHttpRequest的$http调用,如下所示:
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 a response object similar to a regular $http call // // data – {string|Object} – The response body transformed with the transform functions. // status – {number} – HTTP status code of the response. // headers – {function([headerName])} – Header getter function. // config – {Object} – The configuration object that was used to generate the 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); } // This is only available in XHR2,provide multipart fallback // if necessary xhr.send(file); return deferred.promise; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。