Read file

How to Read a File in HTML?

Reading a file in HTML is an essential task for web developers. The process allows them to access data from external resources and display it on a webpage. Here, we will discuss two methods of reading a file in HTML:

Method 1: Using JavaScript

The first method involves using JavaScript to read a file. Here are the steps:

  • Step 1: Create an HTML file with a script tag that includes the following code:

    function readFile() {
      const file = document.querySelector('input[type=file]').files[0];
      const reader = new FileReader();
      reader.onload = function(event) {
        console.log(event.target.result);
      };
      reader.readAsText(file);
    }
  
  • Step 2: Add an input tag to the HTML file that allows users to select a file:

    <input type="file" onchange="readFile()">
  
  • Step 3: Run the HTML file in a web browser and select a file to read.

Method 2: Using jQuery

The second method involves using jQuery to read a file. Here are the steps:

  • Step 1: Download and include the jQuery library in your HTML file:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  
  • Step 2: Create a file input element with an ID and add a click event that triggers the file reading:

    $('#file-input').click(function() {
      $('#file').click();
    });

    $('#file').change(function() {
      const file = $(this)[0].files[0];
      const reader = new FileReader();
      reader.onload = function(event) {
        console.log(event.target.result);
      };
      reader.readAsText(file);
    });
  
  • Step 3: Add the file input element and a hidden input element to your HTML:

    <input type="file" id="file" style="display: none;">
    <input type="button" id="file-input" value="Choose File">
  
  • Step 4: Run the HTML file in a web browser and select a file to read.

Both methods use the FileReader API to read the content of the selected file. The API provides different methods for reading files in various formats, such as text, binary, and data URL. The FileReader API is supported by most modern web browsers, including Chrome, Firefox, Safari, and Edge.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe