Reading a Local File using HTML5 and JavaScript

One area where the web has lacked 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, handling images etc. Some of the specifications 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 Visual Studio (or you can use any HTML editor), 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 here, but we will keep the CSS in the same page for this example

Step 2: In the project add a new folder of name Scripts and add JavaScript file of name FileReaderLogic.js in it, write the below 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 extensio 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 check whether the browser supports File APIs or not. If they are supported then the code reads the File element and subscribe to the change event of it. The change events implementation is as below:
  • Set the file extension to text files only.
  • It 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 secton.

View the page in browser, it will be as below:

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 an standard way to interact with local file system with less complexity.

Will you give this article a +1 ? Thanks in advance


About The Author

Mahesh is having 10 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). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

No comments: