I have the following code:
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// 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>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
I get the data from the file read. How do I read the content and assign it to a variable?
I can't understand the FileReader API
What you are missing is very simple: define readers for the files, and assign the action that will be executed when it is loaded:
It is important to note that the loading is done asynchronously (the code will continue its normal execution and
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 the same, there could be a conflict and the script would fail (or the result might not be what you expected).
Here I leave a demo with the code (look at the console to see the content of the files, if you choose a very large file it may take time to display the content):
In this example you put only extract the information from the file, that is, the metadata. In fact you don't use FileReader just File.
I recommend you read the official w3 API
And you can review the functionality in this jsfiddle (I didn't create it), in the test you can upload a text file and see the content in the browser , which is what you want.
The main trick is to ask if the API is supported and from there execute the Asynchronous process.