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

标签 angularjs

我需要访问原始 XMLHttpRequest对象在支持它的浏览器上添加文件上传进度回调。这是可能的,还是我必须自己构建原始请求?如果是这样,我如何包装原始 XMLHttpRequest在 promise 对象中?

最佳答案

我模拟了$http调用构建自定义 XMLHttpRequest像这样:

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;
}

关于angularjs - 使用 $http 访问原始 XHR 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16532639/

相关文章:

javascript - Chai:如何使用 'should' 语法测试未定义

javascript - 如何在 VSCode 中获取 AngularJS 的智能感知?

javascript - 如何在自定义指令中获取评估属性

java - 具有 Spring Security 的 AngularJS Web 应用程序

javascript - 使用 Node.JS 和 AngularJS 在 HTML 中显示 Redis 值

javascript - AngularJS 隔离范围 ng-model 验证

javascript - 基于所选页面在angularjs中显示/隐藏标题徽章

AngularJS $location 在散列之前获取路径

html - 如何根据 Angular 中的数据动态填充选择框

javascript - 如何在 $http.post() 之后从 Angular 导航到 php 页面