在AngularJS中,有$http.get
来动态获取数据。不幸的是,从官方文档中不易理解如何读取二进制数据(例如,用于图像处理)。
默认get
将数据提取为String
(see it in a plunker)。这是very cumbersome。那么,如何在ArrayBuffer中获取它? (注意,因为XHR2是already possible。)
<!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:如果要提取的图片属于其他域,则可能需要重置标头才能执行simple cross-site request:默认情况下,AngularJS 1.0.6
设置X-Requested-With: XMLHttpRequest
标头,强制preflighted request,即浏览器在OPTIONS
之前发送http GET
请求。服务器可能不支持此功能(例如,在此示例中,服务器返回403 HTTP method not allowed
)。
但是,六个月前This header was removed,(即AngularJS 1.1.1
开启),并且不再需要重置(感谢this answer to AngularJS performs an OPTIONS HTTP request for a cross-origin resource的方式)。
答案 0 :(得分:50)
幸运的是,Vojta Jina已在this feature中实施branch 1.1。以下代码(see it in a plunker)在ArrayBuffer
中获取二进制数据。请注意使用(如今)仍然不稳定的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>
注1和注释2:请参阅原始问题中的注释。