[英]Unable to read data from multiple files using HTML FileReader
<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?
我究竟做错了什么?
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 参考: https : //stackoverflow.com/a/9815648/3088780
I think jquery help you easily 我认为jQuery可以轻松帮助您
HTML: HTML:
<script src="jquery-2.2.0.min.js"></script>
<input type="file" multiple="multiple" />
<ul id="output">
</ul>
Jquery: 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 参考来自: https : //stackoverflow.com/a/7719334/5566169
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.