37

在 AngularJS 中有$http.get动态获取数据的功能。不幸的是,从官方文档中很难理解如何读取二进制数据(例如,用于图像处理)。

默认get以 a 形式获取数据String在 plunker 中查看)。这很麻烦。那么,如何在ArrayBuffer中获取它?(请注意,从 XHR2 开始,这已经成为可能。)

<!DOCTYPE html>
<html>
  <head>
    <title>Using $http.get to read binary data</title>
  </head>
  <body ng-app>
    <h1>$http to load binary data</h1>
    <div ng-controller="FetchCtrl" >
      <button ng-click="fetch()">fetch</button><br/>
      {{info}}
    </div>
    <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
    <script>
    // Controller
    function FetchCtrl($scope, $http) {
      // See note 1
      $scope.URL = "http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png";
      $scope.info = "Click 'fetch' to fetch an image" ;

      $scope.fetch = function() {
        delete $http.defaults.headers.common['X-Requested-With']; // See note 2
        $http.get($scope.URL).
          success(function(data) {
            $scope.info = "Read '" + $scope.URL + "' with " + data.length
            + " chars in a variable of type '" + typeof(data) + "'";
          }).error(function(data, status) {
            $scope.info = "Request failed with status: " + status;
          });
      };
    }      
    </script>
  </body>
</html>

注 1:原始文件大小为 473.831 字节。
注意 2:如果要获取的图像属于不同的域,则可能需要重置标头以执行简单的跨站点请求:默认情况下,AngularJS 1.0.6设置X-Requested-With: XMLHttpRequest标头,强制进行预检请求,即浏览器OPTIONS在之前发送 http 请求GET. _ 服务器可能不支持此功能(如本例中,服务器返回 a 403 HTTP method not allowed)。
不过,此标头在六个月前已被删除(即从AngularJS 1.1.1开始),并且不再需要重置(顺便感谢对 AngularJS 的回答执行 OPTIONS HTTP 请求以获取跨域资源)。

4

1 回答 1

54

幸运的是,Vojta Jina已经在分支 1.1中实现了这个功能。以下代码(在 plunker 中查看)获取. 注意使用(就今天而言)仍然不稳定:ArrayBufferAngularJS 1.1.5

<!DOCTYPE html>
<html>
  <head>
    <title>Using $http.get to read binary data</title>
  </head>
  <body ng-app>
    <h1>Using $http.get to read binary data</h1>
    <div ng-controller="FetchCtrl" >
      <button ng-click="fetch()">fetch</button><br/>
      {{info}}
    </div>
    <script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script>
    // Controller
    function FetchCtrl($scope, $http) {
      // See note 1
      $scope.URL = "http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png";
      $scope.info = "Click 'fetch' to fetch an image" ;
      $scope.fetch = function() {
        delete $http.defaults.headers.common['X-Requested-With']; // See note 2
        $http.get($scope.URL, {responseType: "arraybuffer"}).
          success(function(data) {
            $scope.info = "Read '" + $scope.URL + "' with " + data.byteLength
            + " bytes in a variable of type '" + typeof(data) + "'";
          }).
          error(function(data, status) {
            $scope.info = "Request failed with status: " + status;
          });
      };
    }      
    </script>
  </body>
</html>

注 1 和注 2:见原始问题中的注解。

于 2013-05-28T11:48:35.460 回答