Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
File and FileReader in JavaScript?
The File and FileReader APIs in JavaScript allow web applications to read and process files selected by users. The File object represents file information, while FileReader enables reading file contents asynchronously.
File Object Properties
When a user selects a file through an input element, you get access to a File object with these key properties:
- name - The file's name
- size - File size in bytes
- type - MIME type of the file
- lastModified - Last modification timestamp
FileReader Methods
FileReader provides several methods to read file contents:
-
readAsText()- Reads file as text -
readAsDataURL()- Reads file as data URL (base64) -
readAsArrayBuffer()- Reads file as array buffer -
readAsBinaryString()- Reads file as binary string
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File and FileReader Demo</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 20px;
}
.file-info {
background: #f5f5f5;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
.file-content {
background: #e8f4fd;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
max-height: 200px;
overflow-y: auto;
}
.error {
color: red;
background: #ffe6e6;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>File and FileReader in JavaScript</h1>
<input type="file" accept="text/*" onchange="handleFileSelect(this)">
<div id="fileInfo"></div>
<div id="fileContent"></div>
<div id="error"></div>
<h3>Select a text file to view its details and content</h3>
<script>
function handleFileSelect(input) {
const file = input.files[0];
const fileInfoDiv = document.getElementById('fileInfo');
const fileContentDiv = document.getElementById('fileContent');
const errorDiv = document.getElementById('error');
// Clear previous results
fileInfoDiv.innerHTML = '';
fileContentDiv.innerHTML = '';
errorDiv.innerHTML = '';
if (!file) {
return;
}
// Display file information
fileInfoDiv.innerHTML = `
<div class="file-info">
<h3>File Information:</h3>
<p><strong>Name:</strong> ${file.name}</p>
<p><strong>Size:</strong> ${file.size} bytes</p>
<p><strong>Type:</strong> ${file.type || 'Unknown'}</p>
<p><strong>Last Modified:</strong> ${new Date(file.lastModified).toLocaleString()}</p>
</div>
`;
// Create FileReader instance
const reader = new FileReader();
// Set up event handlers
reader.onload = function(e) {
fileContentDiv.innerHTML = `
<div class="file-content">
<h3>File Content:</h3>
<pre>${e.target.result}</pre>
</div>
`;
};
reader.onerror = function(e) {
errorDiv.innerHTML = `
<div class="error">
<strong>Error reading file:</strong> ${e.target.error}
</div>
`;
};
reader.onprogress = function(e) {
if (e.lengthComputable) {
const percentLoaded = Math.round((e.loaded / e.total) * 100);
fileContentDiv.innerHTML = `<p>Loading... ${percentLoaded}%</p>`;
}
};
// Start reading the file
reader.readAsText(file);
}
</script>
</body>
</html>
FileReader Events
FileReader provides several event handlers for different stages of file reading:
-
onload- Fires when reading completes successfully -
onerror- Fires when an error occurs -
onprogress- Fires periodically during reading (useful for large files) -
onloadstart- Fires when reading starts -
onloadend- Fires when reading ends (success or failure)
Reading Different File Types
<script>
function readAsDataURL(file) {
const reader = new FileReader();
reader.onload = function(e) {
// For images, you can set this as src of an img element
console.log('Data URL:', e.target.result);
};
reader.readAsDataURL(file);
}
function readAsArrayBuffer(file) {
const reader = new FileReader();
reader.onload = function(e) {
const arrayBuffer = e.target.result;
console.log('Array buffer length:', arrayBuffer.byteLength);
};
reader.readAsArrayBuffer(file);
}
</script>
Error Handling
Always implement proper error handling when working with FileReader:
<script>
function safeFileRead(file) {
if (!file) {
console.error('No file selected');
return;
}
// Check file size (example: limit to 5MB)
if (file.size > 5 * 1024 * 1024) {
console.error('File too large');
return;
}
const reader = new FileReader();
reader.onerror = function() {
console.error('Failed to read file:', reader.error);
};
reader.onload = function() {
console.log('File read successfully');
};
reader.readAsText(file);
}
</script>
Browser Compatibility
The File and FileReader APIs are well-supported across modern browsers. FileReader has been available since Internet Explorer 10, making it safe for most web applications.
Conclusion
The File and FileReader APIs provide powerful client-side file handling capabilities. Use FileReader's various read methods and event handlers to process different file types safely and efficiently in your web applications.
