gpt4 book ai didi

javascript - 使用angularjs提取字节数组中的多个文件内容

转载 作者:行者123 更新时间:2023-11-28 04:19:49 28 4
gpt4 key购买 nike

我正在使用此解决方案将文件解析为字节数组:
这对我有用。
但我想对多个文件执行此操作

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

pniotApp.controller('pniotCtrl', function ($scope, $http, $location) {
$scope.saveContent = function ($fileContent) {
$scope.content = $fileContent;
console.log($scope.content);
};
});

pniotApp.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);
var result = [];
for (var i = 0; i < uint8.length; i++) {
result.push(uint8[i]);
}

scope.$apply(function () {
fn(scope, {
$fileContent: result
});
});
};

reader.readAsArrayBuffer((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<input on-read-file="saveContent($fileContent)" type="file"/>

现在我想对多个文件执行此操作。我尝试替换行 reader.readAsArrayBuffer((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
与:

 for (j = 0; j < (onChangeEvent.srcElement || onChangeEvent.target).files.length;j++)
reader.readAsArrayBuffer((onChangeEvent.srcElement || onChangeEvent.target).files[j]);


但我收到此错误
Uncaught DOMException: 无法在“FileReader”上执行“readAsArrayBuffer”:该对象已忙于读取 Blob。

最佳答案

Failed to execute 'readAsArrayBuffer' on 'FileReader': The object is already busy reading Blobs.

我认为这是正确的行为。您应该一个接一个地读取文件并重新创建 Reader a.e.

var reader = new FileReader();

所以相反:

for (j = 0; j < (onChangeEvent.srcElement || onChangeEvent.target).files.length;j++)
reader.readAsArrayBuffer((onChangeEvent.srcElement || onChangeEvent.target).files[j]);

应该是这样的:

 var files = (onChangeEvent.srcElement || onChangeEvent.target).files;
for (j = 0; j < files.length;j++){
readerEngine(files[j]);
}

其中readerEngine是:

function readerEngine(file_){
var reader = new FileReader();
reader.onload = function (onLoadEvent) {
var buffer = onLoadEvent.target.result;
var uint8 = new Uint8Array(buffer);
var result = [];
for (var i = 0; i < uint8.length; i++) {
result.push(uint8[i]);
}

scope.$apply(function () {
fn(scope, {
$fileContent: result
});
});
};

reader.readAsArrayBuffer(file_);
}
<小时/>

没有测试

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

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