Welcome to a quick tutorial and examples of how to read files in Javascript. Yes, you read that right – It is possible to read files in client-side Javascript.
To read a file in Javascript:
- Create an HTML file field –
<input type="file" id="picker">
- Get the selected file –
let selected = document.getElementById("picker").files[0];
- Read the selected file.
let reader = new FileReader();
reader.addEventListener("loadend", () => { let data = reader.result; });
reader.readAsText(selected);
That covers the quick basics, and the file reader is also capable of reading images and binary data. Read on for more examples!
TABLE OF CONTENTS
JAVASCRIPT READ FILES
All right, let us now get into the examples of reading files in Javascript.
EXAMPLE 1) READ AS TEXT
1A) THE HTML
<input type="file" value="Choose TXT File" id="demoPickA"
accept="text/plain" onchange="readFileA()">
<div id="demoShowA"></div>
For this first example, we have a simple “choose file” button, and a <div>
to show the contents of the selected text file.
1B) THE JAVASCRIPT
function readFileA () {
// (A) GET SELECTED FILE
let selected = document.getElementById("demoPickA").files[0];
// (B) READ SELECTED FILE
let reader = new FileReader();
reader.addEventListener("loadend", () => {
document.getElementById("demoShowA").innerHTML = reader.result;
});
reader.readAsText(selected);
}
This is pretty much the “full version” of the snippet in the introduction, and it should be self-explanatory –
- Get the selected file from the input field
- Read the file and display the contents in
<div id="demoShowA">
.
1C) THE DEMO
EXAMPLE 2) READ AS DATA URL (IMAGE)
2A) THE HTML
<input type="file" value="Choose Image File" id="demoPickB"
accept="image/*" onchange="readFileB()">
<img id="demoShowB">
Take note that the file field is now restricted to images, and we use an empty <img>
to display the selected image instead.
2B) THE JAVASCRIPT
function readFile() {
// (A) GET SELECTED FILE
let selected = document.getElementById("demoFile").files[0];
// (B) READ SELECTED FILE
let reader = new FileReader();
reader.addEventListener("load", () => {
let imgTag = document.getElementById("demoShowB");
imgTag.src = reader.result;
});
reader.readAsDataURL(selected);
}
Look no further, we are pretty much only using readAsDataURL()
instead of readAsText()
in this example. This will directly get the file data as a base64 encoded string – Rather useful for doing things like “preview selected image”.
2C) THE DEMO
EXAMPLE 3) READ AS BINARY DATA
3A) THE HTML
<input type="file" value="Choose File" id="demoPickC"
onchange="readFileC()">
3B) THE JAVASCRIPT
function readFileC () {
// (A) GET SELECTED FILE
let selected = document.getElementById("demoPickC").files[0];
// (B) READ SELECTED FILE
let reader = new FileReader();
reader.addEventListener("load", () => {
var bindata = reader.result;
console.log(bindata);
});
reader.readAsBinaryString(selected);
}
This should be getting stale now – Use readAsBinaryString()
to read the file as a binary string. I personally can’t think of a good simple example for this… But this will come in handy for raw data processing and exchange. Maybe create a new blob
object, convert it into a ReadableStream
.
EXAMPLE 4) READ AS ARRAY BUFFER
4A) THE HTML
<input type="file" value="Choose File" id="demoPickD"
onchange="readFileD()">
4B) THE JAVASCRIPT
function readFileD () {
// (A) GET SELECTED FILE
let selected = document.getElementById("demoPickD").files[0];
// (B) READ SELECTED FILE
let reader = new FileReader();
reader.addEventListener("load", () => {
var buffer = reader.result;
console.log(buffer);
console.log(buffer.byteLength);
});
reader.readAsArrayBuffer(selected);
}
Finally, we have readAsArrayBuffer()
, read the file as an ArrayBuffer
. Again, I don’t have a good simple example for ArrayBuffer
here – That is out of topic for this tutorial, and it is a boring low-level operation (binary processing). Will leave a link below if you are interested.
EXAMPLE 5) OPEN FILE PICKER PROGRAMMATICALLY
<script>
async function readFileE () {
// (A) OPEN FILE PICKER
[handler] = await window.showOpenFilePicker({
excludeAcceptAllOption: true,
types: [{
description: "Text",
accept: { "text/plain": [".txt", ".text"] }
}]
});
// (B) GET SELECTED FILE
let selected = await handler.getFile();
// (C) READ SELECTED FILE
let reader = new FileReader();
reader.addEventListener("loadend", () => {
document.getElementById("demoShowE").innerHTML = reader.result;
});
reader.readAsText(selected);
}
</script>
<input type="button" value="Choose File" onclick="readFileE()">
<div id="demoShowE"></div>
Lastly, we can use window.showOpenFilePicker()
to open the “choose a file” dialog box in Javascript. But please take note that it will only work on Chrome, Edge, and Opera at the time of writing – CanIUse.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here to download. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- File Reader – CanIUse
- Show Open File Picker – CanIUse
Yep, reading files is not for the old Internet Exploders.
LINKS & REFERENCES
- File Access API – MDN
- File Reader – MDN
- ArrayBuffer, binary arrays – Javascript.info
- Ways To Read Files In NodeJS – Code Boxx
TUTORIAL VIDEO
INFOGRAPHIC CHEATSHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Thanks for simple but direct and informative coding tutorial. This is how code must be.
Sorry this post, although seemingly simple, is completely incomprehensible. Bravo your language is simple, but the problem is that you start from the assumption that those reading knows WHERE to create an HTML field. Again language is simple but I haven’t a flipping clue where I am supposed to do this. I have only one problem, I have a load of files in .js (long story having to do with a website) and all I want to do is read them, in plain english, not code.
Anyway thanks
“I came to a coding tutorial but don’t want to read code. Laplace transformation should be as simple as 1 + 1 = 10.”
“It’s not my fault that I skipped all the basics. I just assume that programming is not technical.”
Have you not realized that the problem lies within and not outside? 😆
P.S. Manage your own expectations. Just hire a web developer if you are so unwilling to learn. Cheers!
Hi and thanks for this. In 5) Pick file example there is a typo which breaks the code.
async function readFileE () {
The E is in Caps.
onclick=”readFile()”
So it gives error : Uncaught ReferenceError: readFile is not defined
Thanks for reporting. Tutorial updated.