I try to save the contents of multiple text files to an array variable using only pure JavaScript. I found some similar questions and answers here on Stackoverflow and tried this and that, without success. Maybe this question is easy to answer, but I'm a beginner, please be tolerant.
Here is my code:
<script>
fileContents=new Array();
function getThem(){
var allFiles=document.getElementById("fileInput").files;
for(var allFilesCounter=0;allFilesCounter<allFiles.length;allFilesCounter++){
function readFile(file){
var reader=new FileReader();
reader.onload=function(){
alert(reader.result);
fileContents[fileContents.length]=reader.result;
};
reader.readAsText(file,"UTF-8");
};
};
};
</script>
<input type="file" accept="text/plain" id="fileInput" multiple="multiple" onChange="getThem();">
I already found out that the FileReader works "asynchronous", which seems to require that all processing of the file content is done inside the reader.onload-function. "alert" does work, as well as other processing, but not assigning the content to the global variable, that's "fileContents[fileContents.length]" in my case.
Is it achievable with that rather simple code, or should I accept that it is not possible to get the file contents saved to a variable (which seems to me to be the most simple and elegant way, but probably I'm wrong).
Thank you in advance for your help.