-1

I was trying to use FileReader to read from a text file and below is my code which throws an error.

var message = document.getElementById("message");
function upFiles(files){
          for(var x=0; x< files.length; x++){
              var fReader = new FileReader();
              fReader.onload = function(e){
                message.innerHTML += '<br>'+ files[x].name;
                 message.innerHTML += '<br>'+e.target.result;
                 
              }
              fReader.readAsText(files[x]);
              
          }

          
      }
<input type="file" multiple onchange="upFiles(this.files)">
<div id-"message"></div>

But when I used a separate variable to store file's name, it worked.

var message = document.getElementById("message");
function upFiles(files){
          for(var x=0; x< files.length; x++){
              var fReader = new FileReader();
              var fileName = files[x].name;
              fReader.onload = function(e){
                message.innerHTML += '<br>'+ fileName;
                 message.innerHTML += '<br>'+e.target.result;
                 
              }
              fReader.readAsText(files[x]);
              
          }

          
      }
 <input type="file" multiple onchange="upFiles(this.files)">
 <div id="message"></div>

I want to know why it worked the second time. why the anonymous function couldn't access the local variable in the first attempt

  • Which part of `Uncaught ReferenceError: message is not defined` do you not understand? You have not defined any such variable, hence the error. – Angel Politis Apr 29 '18 at 15:24
  • 1
    Actually it doesn't really work. It only works when the `files` array has exactly one entry. You would need to use `let`. – Bergi Apr 29 '18 at 16:06
  • Even with the defined variable as var message = document.getElementById('message'); you still get an error. The problem lies within not being able to access files[x].name directly inside the anonymous class – Varuni Punchihewa Apr 30 '18 at 15:41

1 Answers1

0

It doesn't work because you have

            message.innerHTML += '<br>'+ fileName;
             message.innerHTML += '<br>'+e.target.result;

but nowhere in here do you say

var message = ... // whatever message is supposed to be - hopefully something DOM related lol
Deryck
  • 7,608
  • 2
  • 24
  • 43
  • Yeah there's a part where var message = document.getElementById('message'); my bad for not including it! But the problem lies not with the variable declaration rather with accessing files[x].name directly – Varuni Punchihewa Apr 30 '18 at 15:36