Reading Local Files with JavaScript

In this tutorial, we will explore how to read local files using JavaScript. This is a common requirement in web applications where users need to upload or select files from their local system.

Introduction to File Reading in JavaScript

JavaScript provides an API called the File Reader API, which allows you to read the contents of a file. However, due to security reasons, modern browsers do not allow direct access to the user’s file system. Instead, the user must explicitly select the file they want to read through an input element.

Using the FileReader API

The FileReader API is used to read the contents of a file. Here’s an example of how you can use it:

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.textContent = contents;
}

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>

In this example, we first get a reference to the selected file using e.target.files[0]. We then create a new instance of the FileReader object and set its onload event handler. When the file is loaded, the onload event is triggered, and we can access the contents of the file using e.target.result.

Reading Files Using Promises

You can also use promises to read files asynchronously. Here’s an example:

function readFile(file) {
  return new Promise((resolve, reject) => {
    let fr = new FileReader();
    fr.onload = x => resolve(fr.result);
    fr.readAsText(file);
  });
}

async function read(input) {
  msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)" />
<h3>Content:</h3>
<pre id="msg"></pre>

In this example, we define a readFile function that returns a promise. The promise is resolved when the file is loaded, and we can access the contents of the file using the await keyword.

Browser Compatibility

The File Reader API is supported by most modern browsers, including Internet Explorer 10+, Firefox 3.6+, Chrome 13+, and Safari 6.1+. You can check the compatibility of your browser on the Can I Use website.

Conclusion

In this tutorial, we have learned how to read local files using JavaScript. We explored the FileReader API and saw examples of how to use it to read the contents of a file. We also learned how to use promises to read files asynchronously. By following these examples, you can easily integrate file reading functionality into your web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *