Understand HTML5 FileReader API to Upload Image and Text Files

Article By Digamber Rawat on

HTML5 FileReader API

In this tutorial, I am going to share with you how you can use HTML5 FileReader API to upload images and text files from the client side in the web browser. HTML5 FileReader API provides a convenient way to communicate with local files through the local device. HTML5 FileReader API allows you to upload files or blob in the browser very easily.

What HTML5 FileReader API can do for us?

  • Single file upload
  • Multiple file upload
  • File reader allows uploads file using drag and drop
  • Save file reference for offline users
  • Restrict files upload quantity
  • Restrict files size limit
  • Provides file’s mimetype information
  • Allows to creates images thumbnail preview
  • Allow upload text file from client side
  • Helps to display file upload progress
  • Allow uploading any type of File or Blob

1 – Understand Main Objects of HTML5 File API?

The JavaScript FileReader API works asynchronously, It allows a user to upload single or multiple files in the browser via the local device. When a user selects the files from the device then a FileList object is generated and it contains all the selected files within the FileList object.

Let’s understand HTML5 file API

FileList:

The FileList object contains the list of files, these files are uploaded via the local device.

File:

A File is a single object uploaded via the local device. The File object belongs to the FileList object, a File object contains the file’s following information.

File(4701) {
   lastModified: "",
   lastModifiedDate: {},
   name: "",
   size: "",
   type: "",
   webkitRelativePath: "",
}

Blob:

The Blob is also known as Binary Large Object, BLOB object is very useful it keeps the content of the file when uploaded via the local device.

2 – What are the core Methods of HTML5 FileReader API?

Below are the main methods we use for FileReader API.

FileReader Object

The FileReader() object helps you create a new FileReader. The FileReader API offers various asynchronous methods to read File or Blob objects. These methods are very helpful when you are working with large sized files. JavaScript file API allows you to create a new instance from HTML5 FileReader object.

let reader = new FileReader();

We have successfully created a reader instance from FileReader object, now we can easily access FileReader API’s methods.

Let’s get to the business!

readAsDataURL() method

The readAsDataURL() method consumes a File or Blob and generates a base64 encoded data string. This data URL can be used to display the thumbnail preview in web and mobile browsers locally.

var preview = document.querySelector('img'); // Image reference
var file = document.querySelector('input[type=file]').files[0];  // File refrence

var reader = new FileReader(); // Creating reader instance from FileReader() API

reader.addEventListener("load", function () { // Setting up base64 URL on image
    preview.src = reader.result;
}, false);

reader.readAsDataURL(file); // Converting file into data URL

readAsText() method

  • The readAsText() method is used to read text files. This method comes with two parameters
  • The first parameter is used for the File or Blob from which data has to be read. The second parameter defines the string encoding which is to be used for the returned data. If this parameter is not declared then it will take UTF-8 as a default parameter.
var reader = new FileReader();

reader.addEventListener("load", function () {
    var fileText = reader.result;
}, false);

reader.readAsText(file, encoding);

abort() method

The abort() method aborts the read operation. This is very useful when reading large files.

var reader = new FileReader();

reader.abort();

readAsBinaryString() method

The readAsBinaryString() method gets the raw binary data from the file. This method is fully capable of reading any kind of File or Blob.

var reader = new FileReader();

reader.addEventListener("load", function () {
     var dataString = reader.result;
}, false);

reader.readAsBinaryString(file);

readAsArrayBuffer() method

The readAsArrayBuffer() method generates an ArrayBuffer via reading a File or Blob object. It returns Int8Array, Uint8Array, and byteLength arrays. The readAsArrayBuffer method is very helpful when converting images from one extension to another extension e.g. JPEG to PNG or vice versa.

var reader = new FileReader();

reader.addEventListener("load", function () {
   var dataString = reader.result;
}, false);

reader.readAsArrayBuffer(file);

3 – How to Work with HTML File Input Attribute?

Selecting a file through the local device is pretty straightforward, we just have to call the file input type using the HTML element. After that HTML5 filereader api will access the file. The following code will generate the file input field.

<input type="file" >

Setup onchange Event Listener with File Input Field

Once the file input field is generated, then don’t forget to add the onchange event listener. This event listener will trigger the given function when the file input field is used to upload the files.

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

Selecting Multiple Files

Use multiple tag along with, a file input field to select multiple files.

<input type="file" onchange="showFiles(event)" multiple>

4 – How to Check HTML5 File API’s Browser Support?

There are some old browsers which don’t support HTML5 File API, we are going to put a check. This check will alert the users if their browser doesn’t support HTML5 File API.

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // write your code here!
} else {
  alert('Your browser is too old to support HTML5 File's API.');
}

You can use Modernizr tool as well

5 – How to Allow only Images to Select via HTML’s File Input Field?

There are multiple methods through which we can allow only images or any specific files to upload from users device, but I am going to share with you the easiest way through which you can achieve this functionality pretty easily.

01 – Allow only specific image type or extension to select via form file input field.

Include accept="image/x-png,image/gif,image/jpeg" tag to file input field. Whichever image file type extensions you include within accept attribute, will allow access to be uploaded via the user device.

HTML

<input type="file" accept="image/x-png,image/gif,image/jpeg">

02 – Allow any image type to select via form file input field.

Include accept="image/*" tag to file input field, This will include an image type to be uploaded from users device.

HTML

<input type="file" accept="image/*">

6 – How to Upload Single Image file using JavaScript FileReader API?

HTML File

In order to upload a single image file using JavaScript FileReader API, we must declare a file input HTML element in our HTML file. HTML file element allows a user to select any type of file.

To upload the image file from your browser locally you must bind an onchange() event listener to the file input element. This will trigger the showFile()function when a user uploads the image file from their local system.

<input type="file" onchange="showFile()" accept="image/*"><br><br>
<img src="" width="150" alt="Thumb preview...">

JavaScript File

We are going to create showFile() function in javascript for uploading files using HTML5 file API. Within the below function we see following code var reader = new FileReader(), its a reader instance from FileReader API.

We have set up the onload method with reader instance for setting up demoImage image’s URL to selected image’s URL when the reader instance is loaded. Along with that, we are also passing the image file object to readAsDataURL(file) method using reader instance. By following this method we will also be able to convert a file object into a data URL in JavaScript.

   // Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
function showFile() {
var demoImage = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onload = function (event) {
demoImage.src = reader.result;
}
reader.readAsDataURL(file);
console.log(file)
}
} else {
alert("Your browser is too old to support HTML5 File API");
}

View Demo on CodePen

7 – How to Upload Multiple Image files using HTML5 File Upload API?

HTML

In order to upload multiple image files using HTML5 File Upload API, we must mention an HTML file input field in our HTML file along with multiple HTML tag. This tag will allow users to select multiple files from their local device.

<div id="upload" class="upload">
<input type="file" multiple onchange="showFile()" accept="image/*">
</div>
<ul id="preview"></ul>

JavaScript

   // Check HTML5 File API Browser Support
if (window.File && window.FileList && window.FileReader) {
function showFile() {
var preview = document.getElementById("preview");
var fileInput = document.querySelector("input[type=file]");
for (var i = 0; i < fileInput.files.length; i++) {
var reader = new FileReader();
reader.onload = function(readerEvent) {
var listItem = document.createElement("li");
listItem.innerHTML = "<img src='" + readerEvent.target.result + "' />";
preview.append(listItem);
}
reader.readAsDataURL(fileInput.files[i]);
}
}
} else {
alert("Your browser is too old to support HTML5 File API");
}

View Demo on CodePen

8 – How to Read a Text File from Client Side using HTML5 and JavaScript File API?

HTML

In order to read a text file from client side using HTML5 and JavaScript File API, we must declare a File input field. This tag will allow let the users select a text file from client side.

<div class="upload-wrapper">
<header>
<input type="file" onchange="showFile()">
</header>
<div id="show-text"></div>
</div>

JavaScript

   // Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
function showFile() {
var preview = document.getElementById('show-text');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader()
var textFile = /text.*/;
if (file.type.match(textFile)) {
reader.onload = function (event) {
preview.innerHTML = event.target.result;
}
} else {
preview.innerHTML = "<span class='error'>It doesn't seem to be a text file!</span>";
}
reader.readAsText(file);
}
} else {
alert("Your browser is too old to support HTML5 File API");
}

View Demo on CodePen

9 – Browser compatibility for JavaScript File Reader API

FileReader API is supported by most of the browsers, This API is also being loved by latest browsers as well.

Chrome Firefox Edge Safari Opera
10+ 3.6+ 12+ 6.0+ 11.5+

Browser compatibility source caniuse.com

10 – Some Useful Resources for File Reader API

Digamber Rawat

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me