Read, Edit & Write Files with Client-Side JavaScript

An in depth guide to FileReader API and object URLs.

Lately I’ve been working on a side-project, which was based around reading and manipulating files to generate custom thumbnails for Vivaldi browser’s speed dials. I was able to do it all inside the browser, without any server-side processing, and I want to share with you everything that I’ve learned.

This guide covers:

  • using objectURLs and FileReader to read files from the user’s filesystem

Selecting files from the filesystem

To allow your users to select a file from their device, you will first have to create an input with the type of file.

To actually get the files from this input, you will need to access the files property of the input element. It's best to do that by registering a change event listener on the input element. This way a callback function will be called every time a user selects a file.

The way you do that will depend on the framework you’re using. To make this guide as widely applicable as possible, we will be using vanilla JS.

The resulting selectedFile is a File object.

Properties of files

The file input gives us File objects, so in addition to the contents of the file itself, we have access to some additional information, such as:

  • name - the file's name, including the extension but without the path (e.g. "cat_photo.png")

Files also have two other properties: File.lastModifiedDate and File.webkitRelativePath, the first of which is deprecated and the other non-standard, so you should probably avoid using them. Keep in mind that all of these properties are read-only.

Files & Blobs

In addition to File, javascript has another way of representing files, called Blob

Blob contains a generic file's data, along with information about its size and type. File is actually just a more specialised Blob, used to represent specifically files in a user's filesystem. It inherits all of Blob's methods and properties and contains some additional information about the file's name and last modified date.

These two are basically interchangeable, and you can use one almost everywhere you can use the other. If you absolutely need to convert them though, you can do so using the other type’s constructor.

Reading the contents of files

Okay, so we know how to select and get information about files, but how do we actually read what’s inside them? Well, that depends on what kind of file it is and what you want to do with it. For the purposes of this article, we will only focus on images and text files.

The most flexible and well-supported method of reading a file’s contents is the FileReader API. It’s an event driven API, so instead of simply calling a function and getting the file’s contents, we must take some extra steps.

Let’s start with reading a text file:

  1. First we get the file input element, and register a change event listener on it by assigning a callback function to its onchange property

Quick tip: You can access the reader inside an event handler in multiple ways: reader === e.target === this. Keep in mind that this is not available in arrow functions.

Error Handling

In case of an error, the error event handler is called, and you can find the Error object in reader.error. Possible error codes are:

  • FileError.NOT_FOUND_ERR - the file was not found

Most of the time there is no need to differentiate between these error types, maybe except for ABORT_ERR which is generally harmless and can be ignored.

Ready State

The read operation is asynchronous, so don’t try accessing reader.result right after the readAs call. If you really need to check the reader.result value outside of the load event handler, make sure to first check the value of reader.readyState, which will be one of 3 values:

  • 0 - The reader has been created, but no readAs method was called yet. (EMPTY)

The reader.result property will be populated only in case of a successful read operation. In all other cases it will be null.

The same applies to reader.error which should be accessed inside the error event handler.

FileReader Event Types

We’ve already explored the two most common read event types, now let’s quickly cover the rest. FileReader has six event types:

  • load - triggered when a read operation is successfully completed

You’ve probably noticed that FileReader events work similarly to regular DOM events. I find that thinking about them as such makes it a lot easier to understand their non-linear, asynchronous nature.

💡 Sidenote: Just as with DOM events, it’s possible to register event handlers by using addEventListener, or by assigning a callback function to the "oneventname" property of a reader.

Blob.text()

It’s also worth noting that for reading text files there exists a newer and simpler method: Blob.text(). Remember that File is just a Blob with some added functionality, so it inherits all of Blob's methods, including this one. This means you can use this method on both Blobs and Files.

Doesn’t it look nicer? I think it does, but there’s a catch. This API is quite new and the browser support is still pretty poor.

Working with images

Now that we know how to read text files, let’s move on to something more exciting: images. To illustrate this topic, we’re going to build a simple preview of the selected image.

File types

First let’s make sure that the selected file is actually an image. We can do that with the help of the accept attribute.

The accept attribute, allows you to specify what kind of files the user will be allowed to select. It uses a comma-separated list of unique file type specifiers. Each type specifier can be in one of the following formats:

  • A case-insensitive filename extension, starting with a period (“.”) character. For example: .jpg, .JPEG, .gif, .doc

You can mix and match these to suite your particular use-case.

HTML validation isn’t perfect though. For example, on Windows it will only hide the files not matching your criteria, but you can still select “All files (*.*)” or use drag-and-drop to select any file you want. All of this means that it’s also a good idea to check the file type inside your javascript code.

Or you could set up separate processing flows for different file types

Unfortunately startsWith() and includes() don't work in older browsers like Internet Explorer, so if you need to support them, you might want to look into some workarounds or polyfills.

Also, keep in mind that “any image file” will match (among others):

  • images with less-than-perfect browser support, like webp

So make sure you support all of these functionalities, or explicitly specify only the types you plan on supporting.

Data URLs & Object URLs

To display a selected image, we will need an HTML img and a URL for the img.src attribute. There are two different ways to represent an image file as a URL: a dataURL and objectURL. There are some important differences between the two, so let's quickly run through them.

DataURL

It’s the result of reader.readAsDataURL(). It's a string containing the file's type and the actual binary data of the file, encoded using base64.

It’s format can vary a bit depending on the type of data it represents, but for most files it looks like this: data:<mediatype>;base64,<data>, where <mediatype> is a MIME type and <data> is the base64-encoded file.

Because it actually contains the file’s data, it can be used anywhere after it’s generated, without the need for the original file. Pretty cool!

ObjectURL

Also known as blob URL. It’s the result of URL.createObjectURL(). It is a newer API, but still pretty well supported. It won't however work in IE version 9 and lower.

It’s faster and more concise than FileReader but it comes with its own set of headaches and limitations. In contrast to dataURL, it doesn't contain any file data. It's just a reference to a file. Another important difference is the fact that URL.createObjectURL() is synchronous.

The objectURL has to be revoked when it is no longer needed. The browser will do it automatically when the document is unloaded, however for optimal performance and memory usage, you shouldn’t rely on that behavior, especially in large applications with many objectURLs. Instead you should explicitly call URL.revokeObjectURL() when the url is no longer needed, for example in the image.onload event handler, which we will discuss later.

💡 Sidenote: to get the base64-encoded file data from a dataURL, simply extract the part of the string after the comma, like this: dataUrl.slice(dataUrl.indexOf(",") + 1)

Displaying selected images

Most of the time objectURLs and dataURLs can be used interchangeably, but they each have their own strengths and weaknesses. This means you should probably learn both and choose which one to use on a case-by-case basis. Let’s look at examples of both of them, to get a better feeling for how each one works.

Using FileReader & dataURLs

  1. We register a change event listener on the file input

Using objectURLs

  1. We register a change event listener on the file input

💡 Sidenote: Elsewhere you might see images created by using the Image constructor i.e. const img = new Image(). Most of the time it's equivalent to document.createElement("img") and I've never had any problems with either of them. However there might be some edge cases (described in this StackOverflow thread), which seem to make the latter a more reliable option.

FileList

Before we move on to reading multiple files, let’s clear something up. The files property isn't actually an Array, even though it looks like one 😮. It's a special FileList data type. This means it doesn't have access to the normal array methods (like map, forEach, reduce), so to iterate over the list you will have to get creative. I will show you a few different ways to do this, but if you want to know more, check out this StackOverflow thread.

You might also have noticed that even though we’ve only been working with a singe file (until now), we always had to write files[0]. That's because regardless of whether the multiple attribute is set or not, inputElement.files is always a FileList. This means that even if the input only accepts a single file, you still have to provide the index, which in the case of an only item is 0.

💡 Sidenote: According to the w3c working draft, FileList might be replaced by a regular Array in the near future. Fingers crossed 🤞

The FileList interface should be considered “at risk” since the general trend on the Web Platform is to replace such interfaces with the Array platform object in ECMAScript [ECMA-262]. In particular, this means syntax of the sort filelist.item(0) is at risk; most other programmatic use of FileList is unlikely to be affected by the eventual migration to an Array type.

Reading Multiple Files

By default the file input only allows us to select a single file. To allow selecting multiple files at once, add the multiple attribute to the html element.

In this example I’ll be using FileReader because it's asynchronous and won't block the UI when processing many files. But if you want to you can use objectURLs instead and in most cases you should be fine.

Because we’ve already done most of this before, I’ll only use comments to call out important bits of the code. If you skipped the previous sections, I recommend you go back and catch up, I’ll wait 😉⏳

As you can see, we create a separate FileReader instance for every file. The same could probably be achieved by calling readAsDataURL inside a loadend event handler, but this does the job and is probably faster anyway.

Cheatsheet

Here’s a cheatsheet of the entire file-handling flow, including all classes and methods involved.

Thanks for reading.

If something was unclear, or you would like me to expand on some topic, let me know in the comments

Also, if you’re a Vivaldi fan like I am, check out my Vivaldi Thumbnail Generator, it’s a free tool I created because I was tired of creating thumbnails manually. It uses a lot of the concepts from this post and you can check out the entire source code on GitHub.

I write about web development tips & news. Follow me on twitter for more: twitter.com/HadrysMateusz

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store