0

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.

1 Answer 1

1

You're on the right path but you created the function readFile and didn't make a call to it, that is why you were not getting the file contents, but the function is unnecessary. Bellow there is a working snippet with a simpler code, hope you can understand it.

var fileContents = [];

document.getElementById('fileInput').addEventListener('change', handleFileSelect);

function handleFileSelect (e) {
    var allFiles = e.target.files;
    for (var i = 0; i < allFiles.length; i++) {
        var reader = new FileReader();
        reader.onload = function(e) {
            alert(e.target.result);
            fileContents.push(e.target.result);
        };
        reader.readAsText(allFiles[i]);
    };
};
<input type="file" accept="text/plain" id="fileInput" multiple="multiple" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.