gpt4 book ai didi

angularjs - 如何读取 AngularJS 中 ArrayBuffer 中的二进制数据?

转载 作者:行者123 更新时间:2023-12-03 06:21:37 26 4
gpt4 key购买 nike

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

默认的 getString 形式获取数据 ( 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:如果要获取的图像属于不同的域,则可能需要重置 header 才能执行 simple cross-site request :默认情况下,AngularJS 1.0.6 设置 X-Requested-With: XMLHttpRequest header ,强制 preflighted request ,即浏览器在 GET 之前发送 http OPTIONS 请求。服务器可能不支持此功能(如本例中,服务器返回 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 )。

最佳答案

幸运的是,Vojta Jina已经实现this featurebranch 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:请参阅原始问题中的注释。

关于angularjs - 如何读取 AngularJS 中 ArrayBuffer 中的二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16791295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com