我正在尝试在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>`
答案 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
试试这个:
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;