使用$ http访问原始XHR对象 [英] Access raw XHR object using $http

查看:87
本文介绍了使用$ http访问原始XHR对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to access the raw XMLHttpRequest object to add a file upload progress callback on browsers that support it. Is this possible, or do I have to construct the raw request myself? If so, how do I wrap a raw XMLHttpRequest in a promise object?

推荐答案

我模拟了构建自定义XMLHttpRequest$http调用,如下所示:

I simulated the $http call constructing a custom XMLHttpRequest like 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 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;
}

这篇关于使用$ http访问原始XHR对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆