0
<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
     <!--

     function handleFiles(input)
     {
          for (i = 0; i < input.files.length; i++)
          {
              var reader = new FileReader();
              reader.onload = function() 
              {
                  alert(reader.result)
              };
              reader.readAsText(input.files[i]);
          }
      }

     //-->
</script>

I am trying to display the contents of some files that I upload. It works fine if I select a single file, but if I select multiple files, only the content of one file is displayed, rest all are blank. What am I doing wrong?

Triceratops
  • 643
  • 2
  • 11
  • 17

2 Answers2

2

You just need to amend it slighty to do the following:

<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
function handleFiles(input)
{
    for (var i = 0; i < input.files.length; i++) { //for multiple files          
        (function(file) {
            var name = file.name;
            var reader = new FileReader();  
            reader.onload = function(e) {  
                // get file content  
                var text = e.target.result; 
                alert(text)
            }
            reader.readAsText(file, "UTF-8");
        })(input.files[i]);
    }
}
</script>

Reference: https://stackoverflow.com/a/9815648/3088780

Community
  • 1
  • 1
Snaken
  • 63
  • 7
  • Thanks a lot! I read that reference before but could not understand it as I have just started Javascript today. I did not understand this either but will keep trying till I get it. For now, the issue is resolved, thanks! – Triceratops Feb 14 '16 at 12:17
0

I think jquery help you easily
HTML:

<script src="jquery-2.2.0.min.js"></script>
<input type="file" multiple="multiple" />
<ul id="output">
</ul>

Jquery:

$('input:file[multiple]').change(
    function(e){
        console.log(e.currentTarget.files);
        var numFiles = e.currentTarget.files.length;
            for (i=0;i<numFiles;i++){
                fileSize = parseInt(e.currentTarget.files[i].size, 10)/1024;
                filesize = Math.round(fileSize);
                $('<li />').text(e.currentTarget.files[i].name).appendTo($('#output'));
                $('<span />').addClass('filesize').text('(' + filesize + 'kb)').appendTo($('#output li:last'));
            }
    });

reference from : https://stackoverflow.com/a/7719334/5566169

Community
  • 1
  • 1
Nadimul De Cj
  • 484
  • 4
  • 16