File and FileReader in JavaScript?


Following is the code showing file and fileReader in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>File and FileReader in JavaScript</h1>
<input type="file" accept="text/*" onchange="displayFile(this)" />
<div class="result"></div>
<br />
<div class="sample"></div>
<h3>Click on the above button to display file and its details</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   function displayFile(input) {
      let file = input.files[0];
      resEle.innerHTML += "File name = " + file.name + "<br>";
      resEle.innerHTML += "File size = " + file.size + " bytes <br>";
      resEle.innerHTML += "File type = " + file.type + "<br>";
      var Reader = new FileReader();
      Reader.readAsText(file);
      Reader.onload = function () {
         sampleEle.innerHTML += Reader.result;
      };
      Reader.onerror = function () {
         sampleEle.innerHTML += Reader.error;
      };
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘Choose file’ button and choosing a file −

Updated on: 17-Jul-2020

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements