Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
File and FileReader in JavaScript?
Following is the code showing file and fileReader in JavaScript −
Example
<!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 −

Advertisements