With the coming of HTML5, a lot of features were introduced, one of which is the FileReader API. It is a JavaScript interface that provides a way to read files from client.
In this article, we will explore the FileReader API in JavaScript and give some examples.
What is FileReader API?
The FileReader API is a JavaScript interface that provides a way to read files from the user's computer.
The FileReader API is particularly useful for web applications that require the user to upload files, such as image galleries or document management systems.
By using the FileReader API, you can create applications that allow users to preview uploaded files or display images on a web page without having to first upload the file to a server.
How to use FileReader API?
The FileReader API provides two main methods for reading files:
-
readAsText(): This method reads the contents of a file as a text string. The contents of the file are returned as a string, which can be used in JavaScript code.
-
readAsDataURL(): This method reads the contents of a file as a data URL. A data URL is a special type of URL that includes the contents of a file as a string. This string can be used to display images or other media files on a web page.
Using the FileReader API is quite simple. The first step is to create a new instance of the FileReader object. This can be done using the following code:
const reader = new FileReader();
Once you have created a new instance of the FileReader object, you can use its methods to read files. For example, to read a file as a text string, you can use the readAsText() method, like this:
// Get input elements with type file in your HTML document
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
console.log(reader.result);
};
});
Similarly, to read a file as a data URL, you can use the readAsDataURL() method, like this:
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const dataURL = reader.result;
// Create a new image element
const image = document.createElement('img');
// Set the source of the image to the data URL
image.src = dataURL;
// Append the image to the page
document.body.appendChild(image);
};
});
Conclusion
The FileReader is a useful API in javscript. It provides two main methods for reading files readAsText and readAsDataURL() and previving them in web pages without sending to the sources backend side.
Thank you for reading.