Working with files in JavaScript, Part two: FileReader

In my previous postal service, I introduced using files in JavaScript, focusing specifically on how to get access to File objects. These objects contain file metadata obtained only when the user opts to either upload a file or drags and drops a file onto the web folio. Once yous have files, however, the next step is to read data from them.

The FileReader type

The FileReader type has a single chore: to read data from a file and shop it in a JavaScript variable. The API is intentionally designed to be similar to XMLHttpRequest since both are loading data from an external (outside of the browser) resources. The read is done asynchronously so every bit not to block the browser.

There are several formats that a FileReader tin can create to stand for the file information, and the format must exist requested when asking the file to be read. Reading is washed through calling one of these methods:

  • readAsText() – returns the file contents as plain 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 (adept for binary data such as images)
  • readAsDataURL() – returns the file contents every bit a data URL

Each of these methods initiates a file read similar to the XHR object's transport() method initiating an HTTP request. Equally such, you must heed for the load consequence before starting to read. The result of the read is ever represented by outcome.target.result. For example:

                  var reader = new FileReader(); reader.onload = role(event) {     var contents = event.target.effect;     console.log("File contents: " + contents); };  reader.onerror = function(event) {     panel.error("File could non be read! Code " + upshot.target.fault.code); };  reader.readAsText(file);                                  

This example simply reads the contents of a file and outputs it in plain text to the console. The onload handler is chosen 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 event handler via event.target and it'due south recommended to employ that instead of referencing the reader variable direct. The result property contains the file contents on success and fault contains fault information nearly the failed functioning.

Reading data URIs

You can use the aforementioned bones setup for reading to a information URI. Data URIs (sometimes called data URLs) are an interesting selection if y'all want to, for example, display an image that was just read from disk. You could do so with the following code:

                  var reader = new FileReader(); reader.onload = function(event) {     var dataUri = event.target.result,         img     = certificate.createElement("img");      img.src = dataUri;     document.body.appendChild(img); };  reader.onerror = office(event) {     console.error("File could not be read! Lawmaking " + event.target.fault.code); };  reader.readAsDataURL(file);                                  

This lawmaking simply inserts an image that was read from disk into a folio. Since the information URI contains all of the image data, it tin can be passed straight into the src attribute of an image and displayed on the page. Y'all could, alternately, load the image and draw it onto a <canvass> every bit well:

                  var reader = new FileReader(); reader.onload = function(event) {     var dataUri = issue.target.issue,         context = certificate.getElementById("mycanvas").getContext("2d"),         img     = new Image();       // look until the image has been fully processed     img.onload = part() {         context.drawImage(img, 100, 100);     };     img.src = dataUri; };  reader.onerror = function(event) {     console.fault("File could not exist read! Code " + upshot.target.mistake.lawmaking); };  reader.readAsDataURL(file);                                  

This code loads the epitome data into a new Image object and and then uses that to draw the image onto a canvas (specifying both the width and pinnacle as 100).

Data URIs are generally used for this purpose, but can be used on whatever blazon of the file. The almost common use case for reading a file into a data URI is to brandish the file contents on a web folio immediately.

Reading ArrayBuffers

The ArrayBuffer blazon1 was first introduced every bit role 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 past using a specific view, such every bit Int8Array, which treats the underlying bytes as a drove of viii-fleck signed integers or Float32Array, which treats the underlying bytes as a collection of 32-bit floating point numbers. These are called typed arraystwo, which forcefulness y'all to work with a specific numeric type rather than containing whatever type of data (as with traditional arrays).

Y'all use an ArrayBuffer primarily when dealing with binary files, to have more fine-grained control over the information. Information technology'southward beyond the telescopic of this mail to explicate all the ins and outs of ArrayBuffer, just realize that you can read a file into an ArrayBuffer pretty easily if you demand it. You can laissez passer an ArrayBuffer directly into an XHR object's send() method to send the raw data to the server (you'll have to read this data from the asking on the server to reconstruct the file), so long as your browser fully supports XMLHttpRequest Level 2 3 (near contempo browsers, including Cyberspace Explorer 10 and Opera 12).

Upwardly next

Reading information from a file using a FileReader is pretty unproblematic. If you know how to utilize XMLHttpRequest, at that place'south no reason you tin can't besides be reading information from files. In the next part of this serial, you lot'll larn more than about using the FileReader events and agreement more almost possible errors.

References

  1. ArrayBuffer
  2. Typed Assortment Specification
  3. XMLHttpRequest Level 2

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-book that explains not just concepts, but also real-earth uses of promises.

Download the Free E-book!

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