Working with files in JavaScript, Office ii: FileReader

In my previous postal service, I introduced using files in JavaScript, focusing specifically on how to get admission to File objects. These objects contain file metadata obtained just when the user opts to either upload a file or drags and drops a file onto the web page. Once you take files, however, the next footstep is to read data from them.

The FileReader type

The FileReader type has a single job: to read data from a file and store it in a JavaScript variable. The API is intentionally designed to be like to XMLHttpRequest since both are loading information from an external (outside of the browser) resource. The read is done asynchronously so as not to cake the browser.

There are several formats that a FileReader can create to correspond the file data, and the format must be requested when asking the file to exist read. Reading is done through calling ane of these methods:

  • readAsText() – returns the file contents every bit obviously text
  • readAsBinaryString() – returns the file contents as a string of encoded binary data (deprecated – use readAsArrayBuffer() instead)
  • readAsArrayBuffer() – returns the file contents as an ArrayBuffer (good for binary data such equally images)
  • readAsDataURL() – returns the file contents as a information URL

Each of these methods initiates a file read similar to the XHR object's send() method initiating an HTTP request. As such, y'all must listen for the load event before starting to read. The result of the read is ever represented past event.target.result. For instance:

                  var reader = new FileReader(); reader.onload = function(event) {     var contents = event.target.upshot;     console.log("File contents: " + contents); };  reader.onerror = role(event) {     console.mistake("File could not be read! Lawmaking " + event.target.error.lawmaking); };  reader.readAsText(file);                                  

This example simply reads the contents of a file and outputs it in obviously text to the console. The onload handler is called when the file is successfully read whereas the onerror handler is called if the file wasn't read for some reason. The FileReader instance is available inside of the issue handler via event.target and information technology's recommended to use that instead of referencing the reader variable directly. The issue property contains the file contents on success and fault contains error information nigh the failed functioning.

Reading data URIs

You tin can apply the same basic setup for reading to a data URI. Data URIs (sometimes chosen data URLs) are an interesting option if you desire to, for example, display an image that was just read from disk. You could exercise then with the post-obit code:

                  var reader = new FileReader(); reader.onload = function(consequence) {     var dataUri = result.target.upshot,         img     = document.createElement("img");      img.src = dataUri;     document.torso.appendChild(img); };  reader.onerror = role(event) {     panel.error("File could not be read! Lawmaking " + event.target.mistake.code); };  reader.readAsDataURL(file);                                  

This code only inserts an image that was read from disk into a folio. Since the data URI contains all of the image information, information technology can be passed direct into the src attribute of an image and displayed on the page. You could, alternately, load the image and draw it onto a <canvas> as well:

                  var reader = new FileReader(); reader.onload = function(event) {     var dataUri = event.target.outcome,         context = certificate.getElementById("mycanvas").getContext("second"),         img     = new Paradigm();       // wait until the image has been fully processed     img.onload = function() {         context.drawImage(img, 100, 100);     };     img.src = dataUri; };  reader.onerror = office(consequence) {     panel.error("File could not be read! Code " + event.target.mistake.code); };  reader.readAsDataURL(file);                                  

This code loads the prototype information into a new Epitome object and and so uses that to draw the image onto a canvas (specifying both the width and superlative every bit 100).

Data URIs are by and large used for this purpose, but tin can exist used on whatsoever type of the file. The most common employ case for reading a file into a data URI is to display the file contents on a web folio immediately.

Reading ArrayBuffers

The ArrayBuffer typei was first introduced as part of WebGL. An ArrayBuffer represents a finite number of bytes that may be used to store numbers of any size. The way data is read from an ArrayBuffer is by using a specific view, such as Int8Array, which treats the underlying bytes every bit a collection of viii-scrap signed integers or Float32Array, which treats the underlying bytes equally a collection of 32-scrap floating point numbers. These are called typed arraystwo, which force you to work with a specific numeric type rather than containing whatever type of data (as with traditional arrays).

You lot utilise an ArrayBuffer primarily when dealing with binary files, to have more fine-grained command over the data. It'due south beyond the scope of this postal service to explain all the ins and outs of ArrayBuffer, just realize that you can read a file into an ArrayBuffer pretty easily if you need information technology. You tin can pass an ArrayBuffer straight into an XHR object'southward send() method to send the raw data to the server (you lot'll have to read this data from the asking on the server to reconstruct the file), and so long equally your browser fully supports XMLHttpRequest Level 2 three (nigh recent browsers, including Internet Explorer 10 and Opera 12).

Up next

Reading data from a file using a FileReader is pretty simple. If y'all know how to use XMLHttpRequest, there's no reason you can't besides exist reading data from files. In the next office of this series, you'll learn more about using the FileReader events and agreement more than about possible errors.

References

  1. ArrayBuffer
  2. Typed Array Specification
  3. XMLHttpRequest Level ii

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-volume that explains non but concepts, but likewise existent-world uses of promises.

Download the Free Due east-book!

The community edition of Understanding JavaScript Promises is a free download that arrives in minutes.