Javascript FileReader

3

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 not understand the FileReader API

    
asked by kamome 25.02.2016 в 21:16
source

2 answers

1

This example lets you just extract the information from the file, that is, the metadata. In fact you do not use FileReader only File.

I recommend you read the official w3 API

And you can check the functionality in this jsfiddle (I did not create it), in the test you can upload a text file and view the content in the browser , which is what you want.

The main trick is to ask if the API is supported and then execute the Asynchronous process.

    
answered by 25.02.2016 / 22:17
source
2

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>
    
answered by 25.02.2016 в 22:19