Read local files using JavaScript

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.

Read files in JavaScript

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 is what we get:

Read files in JavaScript

Here I have a test file called "content.txt" lets select that file and see if we cant read its content:

Read text file in JavaScript

JavaScript code:


Results:

Read files in JavaScript

  • 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 :



Post a Comment

0 Comments