DotNetCurry Logo

Read a Local File using HTML5 and JavaScript

Posted by: Mahesh Sabnis , on 8/21/2015, in Category HTML5 & JavaScript
Views: 33020
Abstract: The HTML5 File API provides a standard way to interact with local file system with less complexity. In this article, we will use JavaScript and HTML5 to read a local file.

One area where the web has been lagging for some time is the lack of a true file system.  HTML5 fills this void by providing a standard way of interacting with local files using the FIle API specification.

These APIs are used to read file locally, handle images etc. Some of the specifications of this API are as listed below:

1. File: Provides read-only information about the file like name, filesize, mimetype etc.
2. FileList: Represents an array of individually selected files from the local system
3. Blob: Represents the raw binary data and allows access to range of bytes within the data which can be used for slicing file
4. FileReader: Provides methods to read data from file or Blob

 

Step 1: Open any HTML editor (Sublime, Visual Studio Code), and create a new application. In this application, add a new HTML page and add the following HTML markup in it.

<style type="text/css"> 
     #filecontents { 
          border:double; 
       overflow-y:scroll; 
       height:400px; 
     } 
</style>
<body> 
     Please Select text file of which contents are to be read: 
      <input type="file" id="txtfiletoread" />
    <div>The File Contents are as below:</div> 
     <div id="filecontents">
    </div>
</body>

Note: Ideally you should put the CSS in a separate file and link the file in your HTML, but we will keep the CSS in the same page for this example for the sake of convenience.

Step 2: In the project, add a new folder called Scripts and add a JavaScript file with the name FileReaderLogic.js in it.

Write the following script in it:

window.onload = function () { 
 //Check the support for the File API support 
 if (window.File && window.FileReader && window.FileList && window.Blob) {
    var fileSelected = document.getElementById('txtfiletoread');
    fileSelected.addEventListener('change', function (e) { 
         //Set the extension for the file 
         var fileExtension = /text.*/; 
         //Get the file object 
         var fileTobeRead = fileSelected.files[0];
        //Check of the extension match 
         if (fileTobeRead.type.match(fileExtension)) { 
             //Initialize the FileReader object to read the 2file 
             var fileReader = new FileReader(); 
             fileReader.onload = function (e) { 
                 var fileContents = document.getElementById('filecontents'); 
                 fileContents.innerText = fileReader.result; 
             } 
             fileReader.readAsText(fileTobeRead); 
         } 
         else { 
             alert("Please select text file"); 
         }

    }, false);
} 
 else { 
     alert("Files are not supported"); 
 } 
 }

The code first checks whether the browser supports File APIs or not. If they are supported, then the code reads the File element and subscribes to the change event of it. The change events implementation is as mentioned here:

  • Set the file extension to text files only.
  • Get the file object which is selected by the File element.
  • If the file extension is text, then the FileReader object is initialized.
  • The File is then read using readAsText() method of the FileReader object.
  • The file contents are then displayed in the div of name filecontents.

Step 3: Include the above script file in the HTML page in the Header section.

View the page in browser and you will see the following:

fileapi-html5

Select the file using file element and the result will be as shown here:

read-text-file

Conclusion: The HTML 5 File API provides a standard way to interact with local file system with less complexity. In future articles, we will see some additional use cases of the File API.


 

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!