我使用此解决方案将文件解析为字节数组:
这对我有用。
但我想为多个文件执行此操作
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]);
});
}
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<input on-read-file="saveContent($fileContent)" type="file"/>
&#13;
现在我想为多个文件执行此操作。
我尝试替换行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: Failed to execute 'readAsArrayBuffer' on 'FileReader': The object is already busy reading Blobs.
答案 0 :(得分:0)
无法在'FileReader'上执行'readAsArrayBuffer':对象是 已经忙着读Blob了。
我认为这是一种正确的行为。您应该逐个阅读一个文件并重新创建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_);
}
没有测试