在Javascript中打印多个html文件的输出

时间:2016-02-22 06:07:38

标签: javascript jquery html

我正在尝试在html中打印多个文件。我成功打印了单个文件。但是我无法打印多个文件的文本输出。你能帮我纠正一下代码吗?`

<!DOCTYPE html>

<html>
<body>
<h1> Testing programs </h1>

<input type="file" id="fileinput" multiple />
<pre id="file-content"></pre>
<h3>Contents of the file:</h3>
<script type="text/javascript">

  function readMultipleFiles(evt) {
    //Retrieve all the files from the FileList object
    var files = evt.target.files; 

    if (!files) {
        for (var i=0, f; f=files[i]; i++) {
              var r = new FileReader();
            r.onload = (function(f) {
                return function(e) {
                    var contents = e.target.result;
                    displayContents(contents);
                };
            });

            r.readAsText(f);
        }   
    } else {
          alert("Failed to load files"); 
    }
    function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.innerHTML = contents;
  }

   document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false)
</script>
</body>
</html>` 

2 个答案:

答案 0 :(得分:1)

只需将displayContents方法替换为

即可
function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.innerHTML += contents; //observe + before =
}

因为它需要附加文件而不是替换最后一个

答案 1 :(得分:1)

无需在提供的代码段中使用closure。根据 gurvinder 的建议,使用innerHTML +=

if条件应与if (files)类似,因为如果文件长度大于0

,则为真

试试这个:

&#13;
&#13;
function readMultipleFiles(evt) {
  var files = evt.target.files;
  if (files) {
    for (var i = 0; i < files.length; i++) {
      var r = new FileReader();
      r.onload = function(e) {
        var contents = e.target.result;
        displayContents(contents);
      };
      r.readAsText(files[i]);
    }
  } else {
    alert("Failed to load files");
  }
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.innerHTML += contents;
}

document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
&#13;
<h1> Testing programs </h1>
<input type="file" id="fileinput" multiple />
<pre id="file-content"></pre>
<h3>Contents of the file:</h3>
&#13;
&#13;
&#13;

另请参考这个小提琴:https://jsfiddle.net/rayon_1990/2cwr4c00/