Home  Web-development   The file ap ...

The File API example in browser

The File API in browsers allows web applications to interact with local files selected by the user. This includes reading the contents of files, creating new files, and uploading files to a server. Below is an example that demonstrates how to use the File API to read a file's contents and display it in a web page.

Example: Reading a File and Displaying its Contents

1. HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File API Example</title>
</head>
<body>
  <h1>File API Example</h1>
  <input type="file" id="fileInput">
  <pre id="fileContent"></pre>

  <script src="script.js"></script>
</body>
</html>

2. JavaScript Code (script.js)

document.getElementById('fileInput').addEventListener('change', function(event) {
  const file = event.target.files[0];
  
  if (file) {
    const reader = new FileReader();
    
    reader.onload = function(e) {
      const content = e.target.result;
      document.getElementById('fileContent').textContent = content;
    };
    
    reader.onerror = function(e) {
      console.error('Error reading file:', e.target.error);
    };
    
    reader.readAsText(file);
  } else {
    console.log('No file selected');
  }
});

Explanation

  1. HTML Structure:

    • The HTML includes an input element of type file that allows the user to select a file.
    • A pre element is used to display the file content in a preformatted text block.
  2. JavaScript Code:

    • The JavaScript listens for changes to the file input element. When a file is selected, it triggers the change event.
    • The FileReader API is used to read the contents of the selected file.
    • The reader.onload event handler is called when the file has been read successfully, and the file content is displayed in the pre element.
    • The reader.onerror event handler is called if there is an error reading the file.

Additional File API Features

Reading Other File Types

You can use different FileReader methods to read files in various formats:

Handling Multiple Files

To handle multiple files selected by the user, you can loop through the FileList object:

document.getElementById('fileInput').addEventListener('change', function(event) {
  const files = event.target.files;
  
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const reader = new FileReader();
    
    reader.onload = function(e) {
      const content = e.target.result;
      const fileContentElement = document.createElement('pre');
      fileContentElement.textContent = content;
      document.body.appendChild(fileContentElement);
    };
    
    reader.onerror = function(e) {
      console.error('Error reading file:', e.target.error);
    };
    
    reader.readAsText(file);
  }
});
Published on: Jul 25, 2024, 02:39 AM  
 

Comments

Add your comment