【问题标题】:angularjs - how i can get the content-length headerangularjs - 我如何获得内容长度标头
【发布时间】:2016-11-04 07:46:40
【问题描述】:

我正在对具有 xml 文件的 url 执行 http GET 请求,我需要获取响应标头“Content-Lenght”? 有没有办法得到它?我必须先验证文件的大小,然后才能下载它。

这是我的代码

$http({
     method : "GET",
     url : "http://url/file.xml"
  }).then(function mySucces(data) {

    console.log(response);
    $scope.content = response.data;

  }, function myError(error) {

    console.log(error);
    $scope.content = error.statusText;
  });

【问题讨论】:

    标签: javascript angularjs xml header content-length


    【解决方案1】:

    来自 Angular 文档,https://docs.angularjs.org/api/ng/service/$http

    响应回调获取

    • data – {string|Object} – 使用转换函数转换的响应正文。

    • status – {number} – 响应的 HTTP 状态代码。

    • headers – {function([headerName])} – Header getter 函数。

    • config – {Object} – 用于生成请求的配置对象。

    • statusText – {string} – 响应的 HTTP 状态文本。

    您可以通过使用标头名称调用headers 函数来获取响应标头,在本例中为headers('Content-Type')

    $http({
      method: "GET",
      url: "http://b31fe90a.ngrok.io/xml/XML-Meli.xml"
    }).then(function mySucces(response) {
    
      console.log(response);
      console.log(response.headers('content-type'); // it can be `Content-Type` not sure. but can be any header key.
      $scope.content = response.data;
    
    }, function myError(error) {
    
      console.log(error);
      $scope.content = error.statusText;
    });
    

    【讨论】:

    • 它说标头不是函数
    • 这对我来说不适用于“Content-Length”标头。您的示例显示“Content-Type”,但在询问“Content-Length”时,它只返回null。我还没有找到任何方法让它与“Content-Length”一起使用。
    • @jkjustjoshing 你试过这个吗? stackoverflow.com/questions/38190998/…
    • 小心,即使操作正确,CORS 也可能不允许您访问该标头:stackoverflow.com/a/24073356/1478467
    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    • 2021-12-27
    • 2011-11-17
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多