What is the FileReader in Js?
The
FileReader
in JavaScript is an object that allows web
applications to read the contents of files stored on
the user's computer. It is commonly used for handling
file uploads, allowing users to select files from
their local machine and process or display them in the
browser without needing to upload them to a server.
Read Files Asynchronously: The
FileReader
can read files asynchronously, meaning the
application doesn’t freeze while the file is being
read.
File Types: It can read text, binary data, and images, and it supports different read modes (e.g., text, data URL, or ArrayBuffer).
Event-driven: The
FileReader
uses events like
load
,
error
, and
progress
to notify the application when the file is
successfully read or if an error occurs.
readAsText(file)
: Reads the file as a text string (useful for
text files like
.txt
,
.csv
,
etc.).
readAsDataURL(file)
: Reads the file as a Data URL (useful for images
or binary files, like
.png
or
.jpg
).
readAsArrayBuffer(file)
: Reads the file as an ArrayBuffer (useful for
binary data, such as audio or video files).
javascriptconst fileInput = document.querySelector('input[type="file"]'); const fileReader = new FileReader(); fileInput.addEventListener('change', function() { const file = fileInput.files[0]; if (file) { fileReader.onload = function(event) { console.log('File content:', event.target.result); }; fileReader.onerror = function(error) { console.error('Error reading file:', error); }; // Reading the file as text fileReader.readAsText(file); } });
In this example:
The
FileReader
reads a selected file and logs its content once
it's loaded.
The file input element triggers a file read when the user selects a file.
The
FileReader
API provides a convenient way to handle file data
directly in the browser, making it ideal for
applications that require client-side file processing,
such as image previewing, data visualization, or text
file manipulation.
Here’s an example of how you can use the
FileReader
API to read an image file selected by the user and
display it in an
img
element:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image FileReader Example</title> </head> <body> <h1>Select an image to preview</h1> <input type="file" id="fileInput" accept="image/*"> <br><br> <img id="imagePreview" alt="Image preview will appear here" style="max-width: 300px;"> <script> const fileInput = document.getElementById('fileInput'); const imagePreview = document.getElementById('imagePreview'); const fileReader = new FileReader(); fileInput.addEventListener('change', function() { const file = fileInput.files[0]; if (file && file.type.startsWith('image/')) { fileReader.onload = function(event) { imagePreview.src = event.target.result; // Set the image source to the data URL }; fileReader.onerror = function(error) { console.error('Error reading file:', error); }; // Read the image file as a Data URL fileReader.readAsDataURL(file); } else { alert('Please select an image file.'); } }); </script> </body> </html>
File Input: The user selects an image file through the
<input type="file">
element.
FileReader: The
FileReader
is used to read the selected file as a
Data URL
(which is a base64-encoded string representing the
image).
Image Preview: The
img
element's
src
attribute is set to the Data URL once the image is
loaded, allowing it to be displayed as a preview.
Error Handling: If an error occurs while reading the file, it's logged in the console.
This code allows you to select an image from your local machine, read it using JavaScript, and display it directly on the webpage without uploading it to a server.
Here’s the JavaScript code along with a brief explanation:
javascriptconst fileInput = document.getElementById('fileInput'); const imagePreview = document.getElementById('imagePreview'); const fileReader = new FileReader(); fileInput.addEventListener('change', function() { const file = fileInput.files[0]; if (file && file.type.startsWith('image/')) { fileReader.onload = function(event) { imagePreview.src = event.target.result; // Set the image source to the data URL }; fileReader.onerror = function(error) { console.error('Error reading file:', error); }; // Read the image file as a Data URL fileReader.readAsDataURL(file); } else { alert('Please select an image file.'); } });
File Input: We use
document.getElementById('fileInput')
to get the file input element where the user
selects an image.
FileReader: The
FileReader
object is used to read the file as a Data URL,
which is a base64-encoded string representation of
the image.
Image Preview: The
img
element's
src
is updated with the result of the file read
operation, which is the Data URL of the image.
Event Listeners: The
change
event is triggered when the user selects a file,
and the
onload
event is used to set the image source once the
file is successfully read. If there's an error,
the
onerror
event logs it.
I’ll now go ahead and create a video explaining this code.
Ah, got it! Here's an example of how you can use
JavaScript's
FileReader
API to upload and preview a video file selected by the
user.
javascriptconst fileInput = document.getElementById('fileInput'); const videoPreview = document.getElementById('videoPreview'); const fileReader = new FileReader(); fileInput.addEventListener('change', function() { const file = fileInput.files[0]; if (file && file.type.startsWith('video/')) { fileReader.onload = function(event) { videoPreview.src = event.target.result; // Set the video source to the Data URL }; fileReader.onerror = function(error) { console.error('Error reading file:', error); }; // Read the video file as a Data URL fileReader.readAsDataURL(file); } else { alert('Please select a video file.'); } });
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Video Upload and Preview</title> </head> <body> <h1>Select a video to preview</h1> <input type="file" id="fileInput" accept="video/*"> <br><br> <video id="videoPreview" controls style="max-width: 500px;"> Your browser does not support the video tag. </video> <script> const fileInput = document.getElementById('fileInput'); const videoPreview = document.getElementById('videoPreview'); const fileReader = new FileReader(); fileInput.addEventListener('change', function() { const file = fileInput.files[0]; if (file && file.type.startsWith('video/')) { fileReader.onload = function(event) { videoPreview.src = event.target.result; // Set the video source to the Data URL }; fileReader.onerror = function(error) { console.error('Error reading file:', error); }; // Read the video file as a Data URL fileReader.readAsDataURL(file); } else { alert('Please select a video file.'); } }); </script> </body> </html>
File Input: The file input element allows the user to
select a video file. The
accept="video/*"
ensures only video files can be selected.
FileReader: This is used to read the video file as a Data URL.
Video Preview: The
video
element is used to preview the video. Once the
file is read, the
src
attribute of the video tag is set to the Data URL.
Event Listeners: The
change
event triggers when the user selects a file, and
the
onload
event sets the video source when the file is
loaded.
When a user selects a video, it will automatically
load and play within the
<video>
element without needing to upload it to a server.
To display a local font using JavaScript, you can
follow this example where the user selects a font file
(like
.ttf
or
.otf
),
and the font is applied dynamically to the page.
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Local Font Upload</title> <style> #textPreview { font-size: 24px; margin-top: 20px; } </style> </head> <body> <h1>Select a font file to apply it to the text below</h1> <input type="file" id="fontInput" accept=".ttf,.otf"> <div id="textPreview">This is a text preview that will change with your selected font.</div> <script> const fontInput = document.getElementById('fontInput'); const textPreview = document.getElementById('textPreview'); fontInput.addEventListener('change', function() { const file