Wednesday, October 29, 2014

HTML5 FileReader Example

As you know in javascript it is not allowed to access files from users local machine. If it was allowed by any browser it would be a huge security hole.
But now in HTML5 it is allowed to read files from users machine if the user himself selects the file. You can do this using HTML5s FileReader API.
Below is a quick example which illustrates this functionality. In this example the content of the selected file is read by the FileReader and displayed in below textarea.

<html>
  <head>
    <title>Page Title</title>
    <script>
      function readSingleFile(e) {
       var file = e.target.files[0];
       var reader = new FileReader();
       reader.onload = function(e) {
        var content = reader.result;
        document.getElementById('txt1').innerHTML = content;
       };
       reader.readAsText(file);
      }
    </script>
  <head>
  <body>
    <form action="b.html" method="get">
      <input type="file" id="file1" name="file1" onchange="readSingleFile(event)"/>
      <br/>
      <br/>
      <textarea style="width:400;height:500px;" id="txt1"/></textarea>
    </form>
  </body>
</html>

No comments:

Post a Comment