加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 使用$http访问原始XHR对象

发布时间:2020-12-17 10:26:00 所属栏目:安全 来源:网络整理
导读:我需要访问原始 XMLHttpRequest对象,以在支持它的浏览器上添加文件上载进度回调.这是可能的,还是我必须自己构建原始请求?如果是这样,我如何在promise对象中包装原始XMLHttpRequest? 我模拟了构建自定义XMLHttpRequest的$http调用,如下所示: uploadFile(fi
我需要访问原始 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读