I am writing some application to read the selected files by the user and convert them to base64. I want to get notification when all the files are read in memory. For this purpose I am using Observable
where handle the onload
event of FileReader
and send a complete notification. I am using forkJoin
to run the operation in parallel.
Please see below the code where I am creating Observable
and subscribing to it.
onChange($event: any) {
console.log('No of files selected: ' + $event.target.files.length);
var observableBatch : any = [];
var rawFiles = $event.target.files;
for (var i = rawFiles.length - 1; i >= 0; i--) {
var reader = new FileReader();
var file = rawFiles[i];
var myobservable = Observable.create((observer: any) => {
reader.onload = function (e: any) {
var data = e.target;
var imageSrc = data.result;
console.log('File loaded succesfully.' );
observer.next("File loaded");
observer.complete();
};
});
observableBatch.push(myobservable);
reader.readAsArrayBuffer(file);
}
Observable.forkJoin(observableBatch)
.subscribe(
(m) => {
console.log(m);
},
(e) => {
console.log(e);
},
() => {
console.log("All file(s) loading completed!!!");
}
);
}
Complete sample code is available in plunkr
When I select a single file, onload
function is executed and I get the following console logs
However, when I select multiple files, onload
gets executed only once and the batch operation is not completed. Please see the following console logs
Can somebody help me to understand where I am making the mistake?