What you need is very simple: define readers for the files, and assign the action that will be executed when it loads:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var lectores = new Array(); // los lectores
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate.toLocaleDateString(), '</li>');
// creas un lector para cada fichero o podría haber problemas
lectores[i] = new FileReader();
// define qué quieres que ocurra cuando se cargue el contenido
lectores[i].onload = function(e) {
var contenido = this.result;
console.log(contenido); // mostrar por la consola
}
// leer cada fichero como texto (esto se ejecuta de manera asíncrona)
lectores[i].readAsText(f);
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
It is important to keep in mind that the load is done asynchronously (the code will continue its normal execution and the onload
will not be executed until the file is loaded).
It is also important to use a different reader for each file. If you use it, there could be a conflict and the script would fail (or the result might not be as expected).
Here I leave a demo with the code (look at the console to see the contents of the files, if you choose a very heavy file it may take time to show the content):
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var lectores = new Array();
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate.toLocaleDateString(), '</li>');
lectores[i] = new FileReader();
lectores[i].onload = function(e) {
var contenido = this.result;
console.log(contenido);
}
lectores[i].readAsText(f);
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>