Filereader How to Continue Read Javascript

JavaScript FileReader

Introduction to JavaScript FileReader

In any software system, File handling and file operations are very important. File reading is reading the content or data from the user's host or remote system's file. In web applications, we have a FileReader object which lets us read the contents from the user's computer or system from the files or any other raw data buffer. During this, FileReader uses File or Blob objects from which the data is to be read. In this topic, we are going to learn about JavaScript Filereader as we can get the file objects from three possible ways –

  • When using the <input> element to get the FileList object which consists of the selected files
  • DataTransfer object using drag and drop operation
  • HTMLCanvasElement's mozGetAsFile() API

It is important to know that we can only read the contents from the user's or remote system that too in a secure way. We can never read the file by its pathname using FileReader. We will have to use Ajax for the server-side reading of files along the CORS(Cross-origin resource sharing) permissions if cross-domain file reading is involved in reading files using its pathname in Javascript.

Syntax

The constructor FileReader() returns a newly constructed FileReader object.

FileReader Properties

The FileReader object has some properties which inform about the state or content of that object. All these are read-only properties that cannot be reassigned but only retrieved.

Error – If any of the error occurs while reading a file the DOMException object is returned from FileReader.error property.

ReadyState – This property(FileReader.readyState) helps us determine the current state of FileReader object which can be either 0,1 or 2 which specify particular states mentioned below.

  • EMPTY – 0 – Data is not loaded at all until
  • LOADING – 1 – Data loading is in
  • DONE – 2 – Data reading operation is successfully

Result – FileReader.result returns the contents of the file and can only be used if the reading of the file is completed successfully. The format of returned data depends on the read operation's method.

Event Handlers

Here are the Event handlers mention below

  • FileReader.onabort – Whenever the read operation is aborted that is stoped forcefully then we get onabort event of FileReader object which we can use to handle the abort event.
  • FileReader.onerror – In case if some error occurs while reading the data from the file using FileReader object then onerror event is triggered which can be used to handle and perform the manipulation at the time of error occurrence.
  • FileReader.onload – When the reading operation is successfully completed the onload event is triggered which can be further used to handle the load event.
  • FileReader.onloadstart – We get this event when the reading operation is begun.
  • FileReader.onloadend – When the read operation is successfully completed the onloadend event is triggered.
  • FileReader.onprogress – When the read operation is in progress and data is being read from a Blob content, onprogress event is triggered.

We can listen to all the above events using the addEventListener method as FileReader is itself inherited from the EventTarget.

Example

Let us see an example of how it works –

Code:

            <!DOCTYPE html> <body> <input type='file' onchange='openFileOperation(event)'> <p id = "sample1" ></p> <p id = "sample2" ></p> <p id = "sample3" ></p> <p id = "sample4" ></p> <p id = "sample5" ></p> <script> var openFileOperation = function(event) { document.getElementById("sample1").innerHTML = 'entering openFile()' var input = event.target; var reader = new FileReader(); reader.onloadstart = function(event) { document.getElementById("sample2").innerHTML = 'received event: ' + event.type; }; reader.onprogress = function(event) { document.getElementById("sample3").innerHTML = 'received event: ' + event.type; }; reader.onload = function(event) { document.getElementById("sample4").innerHTML = 'received event: ' + event.type; }; reader.onloadend = function(event) { document.getElementById("sample5").innerHTML = 'received event: ' + event.type; }; reader.readAsDataURL(input.files[0]); }; </script> </body> </html>          

Output:

javascript filereader output 1

After selecting a file output is as follows –

javascript filereader output 2

Methods of JavaScript FileReader

Learn the Methods of javaScript filereader

  • FileReader.abort(): This method aborts or stops the read operation and makes the readyState value to DONE.
  • FileReader.readAsArrayBuffer(): Its returns result attribute contains the ArrayBuffer object once finished which contains all the contents read from the Blob which is started for reading.
  • FileReader.readAsBinaryString(): It returns result attribute containing the string containing raw binary data from the file from which contents are read and an object for reading is specified in Blob format.
  • FileReader.readAsDataURL(): It begins the read operation on Blob content and returns the result attribute containing data which is the file's data represented using URL.
  • FileReader.readAsText(): It begins the read operation from the Blob text and returns the result attribute containing a text string having file contents. We can also mention an optional encoding name.

Example

Let us study the reading of the file by all the above methods with the help of an example.

Code:

            <!DOCTYPE html> <html> <body> <p>Demonstration of FileReader read operation using readAsArrayBuffer() method</p> <input type='file' onchange='openFileReadAsArrayBuffer(event)'> <p>Demonstration of FileReader read operation using readAsDataURL() method</p> <input type='file' accept='image/*' onchange='openFileReadAsDataURL(event)'><br> <img id='output2'> <p>Demonstration of FileReader read operation using readAsText() method</p> <input type='file' accept='text/plain' onchange='openFileReadAsText(event)'><br> <p id="demo"></p> <script> var openFileReadAsArrayBuffer = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var arrayBuffer = reader.result; console.log(arrayBuffer.byteLength); }; reader.readAsArrayBuffer(input.files[0]); }; var openFileReadAsDataURL = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var dataURL = reader.result; var output = document.getElementById('output2'); output.src = dataURL; }; reader.readAsDataURL(input.files[0]); }; var openFileReadAsText = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var text = reader.result; console.log(reader.result.substring(0, 200)); }; reader.readAsText(input.files[0]); }; </script> </body> </html>          

The output of the above code is explained below.

When we choose the file from the first input, it reads the file into an array buffer and the length of the read file that is it's array buffer's length is printed on the console. The output is as follows-

output 3

And it's console value is –

output 4

When we choose the file from the second input then the chosen image file is read as URL and can be seen below the input file tag. The output is as follows –

output 5

When the text file is chosen from third input the output on the browser is as follows –

output 6

Recommended Articles

This is a guide to JavaScript FileReader. Here we discuss the Methods, Properties and the Event Handlers of JavaScript FileReader. You may also have a look at the following articles to learn more –

  1. JavaScript Design Patterns
  2. JavaScript Popup Box
  3. JavaScript setInterval
  4. JavaScript Cursor

wagnercriess.blogspot.com

Source: https://www.educba.com/javascript-filereader/

0 Response to "Filereader How to Continue Read Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel