Search code examples
javascriptjqueryhtmlfileapi

Displaying the content of a file with jQuery and HTML5 file API


I am trying to use the HTML5 file API and jQuery to show the content of a file, but it is not working. I am really new to jQuery, so the problem is probably with my code.

Here is the code I'm using:

    <!DOCTYPE html>
    <html>
    <head>
      <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    </head> 

    <body>
      <input type="file" id="file" /> </br>
      <textarea id="list"></textarea> </br>
      <script> 
        if (window.File && window.FileReader && window.FileList && window.Blob) {
          alert("Si esta soportado el API!");
        } else {
          alert('The File APIs are not fully supported in this browser.');
        }

        var manejarArchivos = function(archivo) {
          var reader = new FileReader();
          reader.onload = function(event) {
          var content = event.target.result;
          alert(content);
        };
        reader.readAsText(archivo);
      }

      try {
        $('#file').change(function() {
          manejarArchivos(this.files);
        });
      }
      catch (e) {
        alert(e);
      }

    </script>
    </body>
    </html>

How can I get this block of code to display the contents of my archivo file?


Solution

  • In your code archivo is a FileList, not a File. You should do something like:

    reader.readAsText(archivo[0]);
    

    instead of

    reader.readAsText(archivo);