🤔 What is the fileReader ?
"The FileReader object lets web applications asynchronously read 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." - MDN web Docs
🤔 So how does it work ?
The user use an upload type input to transfer the data, when we upload it we'll use a addEventListener onChange like this:
💻 A real exemple
Here I'm making a poll app, and before sending the datas into the db, I'm letting the user see the result, I'm using react but this does not really matter, you can do it with vanilla Javascript
HTML side
Here I'm creating a html input element with the type file, I'm using onChange because I'm using react, I'd rather recommend you to add an event listener for the input if you're using something else than react
React way
<input
id="form__cover"
type="file"
onChange={(e) => handleFiles(e, 0)}></input>
Vanilla way
<input
id="form__cover"
type="file"
></input>
And then into the Javascript:
const input = document.getElementById("myElement");
input.addEventListener("change", function(){
//Do something in it
});
The fileReader
const handleFiles = (e) => {
const reader = new FileReader();
let file = e.target.files[0];
So in the code above we:
- First declare the variable reader equals to a new Filreader Object / Instance
- Then with define the file equals to the e (event) target (the element targeted) and then the files[0] because we can have an input with multiple files
reader.readAsDataURL(e.target.files[0]);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function () {
console.log(reader.error);
};
We then here first read the data as Data URL, so the data can be read by the browser as a blob, then we:
- Add an event listener for reader wich listen to the load event and then pass a callback function wich will console log the URL of the file
- Add a error handling with the on error wich is an event listener for error, we then pass a callback function as well and console.log the error returned by the reader
Conclusion
Using this is really interesting since we can for exemple display a profile picture selected by the user before sending it to the DB, wich allow the user to have a better feedback and not wait until the page has been reload or the server sent back the data
Thank you for reading this article 🙏, I hope this was helpful for you
Top comments (0)