How to read binary data in AngularJS in an ArrayBuffer?

Fortunately, Vojta Jina has already implemented this feature in branch 1.1. The following code (see it in a plunker) fetches the binary data in an ArrayBuffer. Note the use of the (as for today) still unstable AngularJS 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>

Note 1 and note 2: see notes in the original question.

Leave a Comment