Javascript filereader

An API that facilitates asynchronous access to file data for developers is known as JavaScript FileReader. This FileReader provides a variety of methods for reading files. Among these methods are readAsArrayBuffer and readAsText; additionally, a load event is initiated when a file has been successfully read. Furthermore, the createObjectURL method from the FileReader Library empowers developers to generate files and store them on the user's device. This approach serves as a practical and efficient means of accessing local file content without the necessity of a server-side back-end.

Use of the Javascript filereader

  • JavaScript represents all documents as a File object when you drag and drop files into the web browser. It chooses files to submit using the file input element.
  • The chosen file can be accessed in JavaScript using the File object. JavaScript uses the FileList object to store the File objects.
  • The FileReader object is used to view a file's content. Remember that the FileReader can only view your chosen files through drag and drop or file input.
  • Syntax

The syntax for the FileReader method is demonstrated without any parameters.

Example

Let fileReader_variable = new FileReader();

How to work javascript filereader

  • Create html, css, and javascript pages or tags as per user requirement.
  • Use input with the file type to select the files and documents.
  • Example
    
    <input onchange = "readFileFunction(this)" type = "file">
    
  • Utilize the JavaScript file variable in conjunction with the input files.
  • Example
    
    function readFileFunction(input_var) {
    
    let file_var = input_var.files[0];
    
    }
    
  • Employ the syntax of JavaScript's FileReader.
  • Example
    
    let fileReader_var = new FileReader();
    
  • Access the file that utilizes it as an input parameter.
  • Example
    
    fileReader_var.readAsText(file_var);
    

    Example

The fundamental file reader demonstration illustrates the static file and presents the necessary information extracted from it. We can display the resultant data in an alert box; alternatively, an error message will be presented if issues arise.

Example

<!DOCTYPE html>

<head>

<title> Javascript filereader  </title>

</head>

<body>

<h3> Javascript filereader Example </h3>

<p> Select the required file in the device </p>

<input onchange = "readFileFunction(this)" type = "file">

<script>

function readFileFunction(input_var) {

let file_var = input_var.files[0];

let fileReader_var = new FileReader();

fileReader_var.readAsText(file_var);

fileReader_var.onload = function() {

alert(fileReader_var.result);

};

fileReader_var.onerror = function() {

alert(fileReader_var.error);

};

}

</script>

</body>

</html>

Output

The images produced display the file name alongside the alert dialog box.

Constructors for JavaScript FileReaders

The JavaScript FileReader API provides multiple constructors that facilitate the creation of FileReader objects. These constructors establish the characteristics of the FileReader object, which encompasses the file intended for reading as well as the type of reading operation to execute.

The FileReader class contains the following key constructors:

  • FileReader:

A new instance of the FileReader object has been instantiated via a constructor function that does not take any parameters. This process sets up the object with its default attributes.

  • FileReader(file Blob):

The function Object is responsible for generating a new FileReader instance and designating the file intended for reading. It is essential to supply a Blob object that represents the file to be processed as the file parameter.

It is important to note that in JavaScript, a file is represented by an object containing immutable, raw data, utilizing a data structure known as a Blob (binary large object). Blobs allow for the storage and transmission of substantial amounts of data, encompassing files, images, and binary information.

  • FileReader(file: Blob, encoding: string):

FileReader Besides establishing the file to be read and determining the file's encoding, this function Object { [native code] } creates a new instance of the FileReader object. The encoding parameter defines the character encoding for the file, which must be a Blob object that corresponds to the file intended for reading.

These constructors serve the purpose of creating and setting up a FileReader instance. By utilizing the appropriate reading method, like readAsArrayBuffer, the instance is capable of accessing the file once it has been established.

Events in a JavaScript FileReader

Programmers have the capability to asynchronously access files stored on a user's device through the JavaScript FileReader API. This functionality is commonly utilized alongside HTML5 file input elements, facilitating the process for users to upload files to a web application.

The JavaScript FileReader has several events that can be used to monitor the progression and conclusion of file reading activities. These things happen like:

  • loadstart: The start of a file reading operation triggers this event.
  • progress: This event is regularly generated while a file is being read, enabling developers to monitor the operation's progress and show the user a progress bar.
  • load: When a file accessing action is completed, this event is fired.
  • abort: This event is launched if the user interrupts or cancels the file reading procedure.
  • error: If a problem reads the file, this event is started.
  • loadend: When a file reading process is finished, whether successful or not, the loadend event is triggered.

Developers have the capability to create intuitive file upload interfaces that provide users with feedback and keep them updated on the status of their file uploads by tracking these events and reacting accordingly.

Properties of a JavaScript FileReader instance

In order to gather information regarding a FileReader object, the JavaScript FileReader API provides a variety of properties. These properties are designed to retrieve information about the file in question, track the progress of the reading process, and report the results of the read operation.

The subsequent properties of the FileReader API's primary instance are as follows:

  • When the FileReader object processes a file, this property returns the DOMException error.

readyState: This property gives the FileReader object's current state. Any of the following numbers could represent it:

  • 0: This indicates that no read action was initiated although the FileReader object was created.
  • 1: It denotes a progressive state for the read process.
  • 2: It indicates that the read process is finished.
  • result: Depending on the type of read operation carried out, this property gives the outcome of the read operation as a string, an ArrayBuffer, or a DataURL.
  • Information of the FileReader object and the file is worked to access using these instance properties. The operator can access instance attributes, such as the reader.error, reader.readyState, and reader.result.
  • Examples

The subsequent examples illustrate the necessary image and file details needed to obtain the value.

Example1

The subsequent illustration demonstrates the data contained within the file alongside the output generated from the selected input file. When we choose a file, whether it be an image or any other type of document, the resulting output displays key details about the file, including its size.

Example

<!DOCTYPE html>

<html>

<head>

<title> JavaScript FileReader Example</title>

<meta charset = "UTF-8">

<script>

function changeHandlerFunction(evnt_data) {

evnt_data.stopPropagation();

evnt_data.preventDefault();

// FileList object.to get output data

var files = evnt_data.target.files;

var file_data = files[0];

var file_dataReader = new FileReader();

file_dataReader.onloadstart = function(progressEvent) {

resetLog();

appendLog("Function onloadstart!");

var msg_output = "File Name: " + file_data.name + "<br>" +

"File Size: " + file_data.size + "<br>" +

"File Type: " + file_data.type;

appendLog(msg_output);

}

file_dataReader.onload = function(progressEvent) {

appendLog("onload!");

var stringData = file_dataReader.result;

appendLog(" ---------------- File Content shows required information ----------------: ");

appendLog(stringData);

}

file_dataReader.onloadend = function(progressEvent) {

appendLog("onloadend!");

// FileReader.EMPTY, FileReader.LOADING, FileReader.DONE

appendLog("readyState = " + file_dataReader.readyState);

}

file_dataReader.onerror = function(progressEvent) {

appendLog("onerror!");

appendLog("Has Error!");

}

// Read file_data asynchronously.

file_dataReader.readAsText(file_data, "UTF-8");

}

function resetLog() {

document.getElementById('log-div').innerHTML = "";

}

function appendLog(msg_output) {

document.getElementById('log-div').innerHTML += "<br>" + msg_output;

}

</script>

</head>

<body>

<h3> Javascript FileReader Example</h3>

<a href = ""> Reset Files </a> <br> <br>

<input type = "file" onchange = "changeHandlerFunction(event)">

<br><br>

<output id = "log-div"> </output>

</body>

</html>

Output

The image below displays details regarding the chosen files.

Example 2:

The example provided illustrates the file's information alongside the data presented on the display using the input file. When we choose a file, whether it be an image or any other type of document, the output will reveal the key details pertaining to that file.

Example

<!DOCTYPE html>

<html>

<head>

<title> JavaScript FileReader Example</title>

<meta charset = "UTF-8">

<script>

function changeHandlerFunction(event_output) {

event_output.stopPropagation();

event_output.preventDefault();

// FileList object.

var files = event_output.target.files;

var file_output = files[0];

var file_outputReader = new FileReader();

file_outputReader.onload = function(progressEvent) {

var url = file_outputReader.result;

console.log(url);

//Show the url image as an output

var myImg = document.getElementById("image_val");

myImg.src= url;

}

// Read file_output asynchronously.

file_outputReader.readAsDataURL(file_output);

}

</script>

</head>

<body>

<h3> Javascript FileReader Example</h3>

<a href = ""> Reset Files </a> <br> <br>

<input type = "file" onchange = "changeHandlerFunction(event)">

<br><br>

<output id = "log-div"> </output>

<img id = "image_val" src = "">

</body>

</html>

Output

The image below displays the details pertaining to the chosen files.

FileReader Instance Methods in JavaScript

The FileReader class in JavaScript provides a variety of instance methods that allow you to extract data from a File or Blob object. The available methods include:

  • abort:

The readyState transitions to 2, indicating that the process is in the DONE or COMPLETED phase, while the abort function halts the ongoing reading operation.

  • readAsArrayBuffer(blob):

The Blob or File object data can be accessed and transmitted as an ArrayBuffer through this instance method. This approach is particularly useful when dealing with binary data or files that you wish to examine in their raw byte format.

  • readAsBinaryString(blob):

Unlike readAsArrayBuffer, this method provides the contents of a Blob or File as a binary string.

  • readAsDataURL(blob):

Data derived from a Blob and a File object can be accessed through this function, which will yield base64-encoded results. This approach can be advantageous for directly displaying images or various file formats in the browser.

  • readAsText(blob, [encoding]):

This approach enables you to retrieve data from a Blob or File object and provide it as a text string. You can also define the encoding of the text.

  • With the exception of abort:

Every method takes either a Blob or a File as its initial argument and synchronously provides the data contained within the file. Consequently, to access the contents of the file, it is necessary to implement the load event handler of a FileReader instance.

Supported web browsers

The following browsers and its version support the JavaScript FileReader.

  • Google Chrome v6.0 and above
  • Mozilla Firefox v3.6 and above
  • Microsoft Edge v12.0 and above
  • Apple Safari v6.0 and above
  • Opera v11.0 and above
  • Conclusion

The FileReader API in JavaScript provides a variety of events that allow developers to track both the progress and completion of file reading operations.

The majority of modern web browsers, such as Chrome, Firefox, Edge, Safari, and Opera, provide support for the FileReader API in JavaScript.

Input Required

This code uses input(). Please provide values below: