Read a Local File using HTML5 and JavaScript
Posted by: Mahesh Sabnis ,
on 8/21/2015,
in
Category HTML5 & JavaScript
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:
Select the file using file element and the result will be as shown here:
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.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn