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?

2 Answers 2

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

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

1 Comment

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!
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

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.