One of the most used web features is the ability to locate and interact with files on the local user's machine. It allows users to select files and upload to the server, for example, upload photos, send tax documents, etc. But it also allows websites to read and process them without having to transfer data over the network.
Local files can be opened and read in the browser using the Javascript FileReader object.
Reading a file from the local fileSystem can be achieved using Javascript by :
Local files can be opened and read in the browser using the Javascript FileReader object.
Reading a file from the local fileSystem can be achieved using Javascript by :
- Choosing a file from the user's system through <input type="file"> element.
- Reading the chosen file using FileReader object.
Here is an example, a simple html page that has an input, "read file" button and a div element to append the file content in it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Read Files With JavaScript</title> | |
</head> | |
<body> | |
<input type="file" id="file-input"/> | |
<button id="read-button">Read File</button> | |
<div id="content"></div> | |
<script type="text/javascript" src="main.js"></script> | |
</body> | |
</html> |
This is what we get:
Here I have a test file called "content.txt" lets select that file and see if we cant read its content:
JavaScript code:
Here I have a test file called "content.txt" lets select that file and see if we cant read its content:
JavaScript code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.getElementById("read-button").addEventListener('click', function() { | |
if(document.getElementById("file-input").files.length == 0) { | |
alert('Error : No file selected'); | |
return; | |
} | |
var file = document.getElementById("file-input").files[0]; | |
var reader= new FileReader(); | |
reader.readAsText(file); | |
reader.addEventListener('load', function(e) { | |
var text = e.target.result; | |
document.getElementById('content').innerText=text; | |
}); | |
}); |
Results:
- The load event handles successful reading of the file.
- The error event handles error while reading the file.
- The progress event handles reading progress of the file.
- Text files (TXT, CSV, JSON, HTML etc) can be read with readAsText() method.
- Binary files (EXE, PNG, MP4 etc) can be read using readAsBinaryString() / readAsArrayBuffer() methods.
Try it yourself :
0 Comments