PROWAREtech
JavaScript: Use FileReader to Read the Contents of Files
The FileReader
object in JavaScript allows reading the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. It is typically used in conjunction with input elements of type file
or via drag-and-drop interfaces. FileReader
provides several methods to read a file as text, a data URL, or a binary array.
Here's a step-by-step guide on how to use FileReader
in JavaScript:
1. Create a File Input Element
First, add an input element for file selection to the HTML:
<input type="file" id="file-input">
2. Set Up a FileReader
Next, set up a FileReader
instance in JavaScript and define the function to run once the file has been read:
var fileInput = document.getElementById("file-input");
fileInput.addEventListener("change", function() {
var file = this.files[0]; // Get the first file selected by the user
if (file) {
var reader = new FileReader();
// Setup the callback for when reading is complete
reader.onload = function(e) {
console.log("File read:", e.target.result);
};
// Setup the callback for any error during reading
reader.onerror = function() {
console.error("Error occurred reading file:", reader.error);
};
// Read the file as Text
reader.readAsText(file);
}
});
FileReader Methods
FileReader
provides several methods for reading a file, each appropriate for different types of data:
-
readAsArrayBuffer(file)
: Reads the file as an ArrayBuffer. Useful for binary data such as images or sounds. -
readAsBinaryString(file)
: Reads the file as a binary string. This method is deprecated. -
readAsDataURL(file)
: Reads the file and returns a base64 encoded string prepended with the data URL. Useful for displaying images or other media directly in web pages. -
readAsText(file, [encoding])
: Reads the file as text. It takes an optional second argument to specify the encoding (default is "UTF-8").
3. Example: Reading an Image as a Data URL
If wanting to display an image right after the user selects it, use readAsDataURL
:
<input type="file" id="image-input">
<img id="preview-image" src="" alt="Preview">
var imageInput = document.getElementById("image-input");
var previewImage = document.getElementById("preview-image");
imageInput.addEventListener("change", function() {
var file = this.files[0];
if (file && file.type.startsWith("image")) {
var reader = new FileReader();
reader.onload = function(e) {
previewImage.src = e.target.result;
};
reader.onerror = function() {
console.error("Error occurred reading image:", reader.error);
};
reader.readAsDataURL(file);
}
else {
console.log("Please select an image file.");
}
});
4. Error Handling
The FileReader
API provides a few events for handling errors:
-
onerror
: Triggered if an error occurs while reading the file. TheFileReader
object’serror
property contains an object describing the error. -
onabort
: Triggered if the read operation is aborted, for example, by callingreader.abort()
.
Conclusion
The FileReader
API is powerful for handling file inputs in JavaScript, enabling web applications to process files on the client side. It is particularly useful for applications that need to read and manipulate files before uploading them to a server, such as image editors, text editors, or data analysis tools.