gpt4 book ai didi

javascript - 使用angularjs提取字节数组中的二进制文件内容

转载 作者:可可西里 更新时间:2023-11-01 09:12:10 24 4
gpt4 key购买 nike

我想将二进制文件中的二进制数据提取到字节数组中。我很难让它正常工作。

您可以在此处查看 jsFiddle:https://jsfiddle.net/alexsuch/6aG4x/

HTML:

<div ng-controller="MainCtrl" class="container">
<h1>Select text file</h1>
<input type="file" on-read-file="showContent($fileContent)" />
<div ng-if="content">
<h2>File content is:</h2>
<pre>{{ content }}</pre>
</div>
</div>

Javascript 代码:

var myapp = angular.module('myapp', []);

myapp.controller('MainCtrl', function ($scope) {
$scope.showContent = function($fileContent) {
$scope.content = $fileContent;
};
});

myapp.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);

element.on('change', function(onChangeEvent) {
var reader = new FileReader();

reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};

reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});

我得到一个损坏的文本格式,如下所示:enter image description here

我做错了什么导致内容变成这样乱码?

最佳答案

您说您希望文件的二进制内容通过 JSON 发送并存储在 mongoDB 中。您的代码的问题是您将文件作为文本读取,而您应该将其作为 ArrayBuffer 读取,这不会将文本编码应用于二进制值。

ArrayBuffer 很棒,但并非所有浏览器都支持通过 XMLHttpRequest 通过 JSON 发送 ArrayBuffer。特别是如果您知道它需要采用的格式,将其转换为常规数组可能是个好主意。幸运的是,我们可以在 JavaScript 中使用类型化数组来帮助实现这一点。

var myapp = angular.module('myapp', []);

myapp.controller('MainCtrl', function ($scope) {
$scope.showContent = function($fileContent) {
$scope.content = $fileContent;
};
});

myapp.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);

element.on('change', function(onChangeEvent) {
var reader = new FileReader();

reader.onload = function(onLoadEvent) {
var buffer = onLoadEvent.target.result;
var uint8 = new Uint8Array(buffer); // Assuming the binary format should be read in unsigned 8-byte chunks
// If you're on ES6 or polyfilling
// var result = Array.from(uint8);
// Otherwise, good old loop
var result = [];
for (var i = 0; i < uint8.length; i++) {
result.push(uint8[i]);
}

// Result is an array of numbers, each number representing one byte (from 0-255)
// On your backend, you can construct a buffer from an array of integers with the same uint8 format
scope.$apply(function() {
fn(scope, {
$fileContent: result
});
});
};

reader.readAsArrayBuffer((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});

更新 fiddle :https://jsfiddle.net/6aG4x/796/

关于javascript - 使用angularjs提取字节数组中的二进制文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37748496/

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