How to Read Files in JavaScript
In most cases, JavaScript does not have direct access to local files on a users machine for obvious security reasons. It is possible, however, to provide the user with the option to select one or many files using an HTML input element, which can then be processed in JavaScript.
In this tutorial, we will learn how to allow to provide users with a way to select files from their machine and then how we can read those files in JavaScript.
Using the input type file
The first step is to create the HTML that will allow the user to select local files. This is done using the HTML input
element with the type
attribute set to file
. We will also give it an ID so it can be accessed easier in JavaScript, in this case the ID will be file_input
but you can use anything you want.
<input type="file" id="file_input">
Allow the User to Select Multiple Files
To allow the user to select more than one file from their machine add the multiple
attribute to the input element.
<input type="file" id="file_input" multiple>
Restrict the Types of Files Allowed
To restrict the file extensions a user is allowed to choose, add the accept=""
attribute containing a comma-separated list of file extensions (each including a preceding .
(dot).)
<input type="file" id="file_input" accept=".txt,.csv" multiple>
Reading the Files in JavaScript
Now we have the HTML set-up we can move on to reading the files in JavaScript after they have been selected. To do this we will get the input
element by its ID, add an event listener to it and look for a change event. When the value of the input changes, it means the user has selected new files and we can go ahead and call a function to read them.
document.getElementById('file_input').addEventListener('change', function processFiles() {
console.log(this.files);
});
FileList {0: File, length: 1}
this.files
is an object called FileList
containing each of the selected files. Each file is a File
object. Before we begin reading each file, let's have a look at the properties on the File
object.
The File Object Properties
The properties that are on a File
object tell us a bunch of useful information about the file in question. In the example below I am getting the first File
object from the FileList
object using this.files[0]
.
console.log(this.files[0]);
{
lastModified: 1602572775120
lastModifiedDate: Tue Oct 13 2020 08:06:15 GMT+0100 (British Summer Time) {}
name: "Instruction.txt"
size: 1567
type: "text/plain"
webkitRelativePath: ""
}
Reading Text Files
Cool, so we can now access metadata about a particular file and see its name, size, type .etc, but how do we actually read data contained in it? To do that we can use the FileReader()
JavaScript function. Let's try this out by reading a plain text file. We will first determine if the files
object is empty and exit the function if true
, otherwise, we will loop through each File
using a for of loop and read it.
apple
strawberry
apricot
orange
document.getElementById('file_input').addEventListener('change', function processFiles() {
if (!this.files.length) {
console.log('0 files selected.');
return;
}
for (let f of this.files) {
const reader = new FileReader();
reader.onload = function readComplete() {
console.log(reader.result);
};
reader.readAsText(f);
}
});
apple
strawberry
apricot
orange
Inside the for of
loop in the example above we a creating a new FileReader
object and saving it in a constant called reader
. Next, we are setting the reader.onload
property to be a function that will display the read result – the onload
property is accessed when FileReader()
has finished reading the file.
We are then telling FileReader()
to read the file using the readAsText()
method.
Read and Display Images
Reading images can be done using a similar method to the example above except this time we will be using the readAsDataURL()
method to read the file into an encoded string. We will also have to create a new img
element, set its src
attribute to the reader.result
and append it somewhere in the body of the HTML document.
document.getElementById('file_input').addEventListener('change', function processFiles() {
if (!this.files.length) {
console.log('0 files selected.');
return;
}
for (let f of this.files) {
const reader = new FileReader();
reader.onload = function readComplete() {
let img = new Image();
img.src = reader.result;
document.body.appendChild(img)
};
reader.readAsDataURL(f);
}
});
Conclusion
You now know how to read files in JavaScript using the HTML input element and the JavaScript FileReader()
function.