Base64 is a great encoding and decoding scheme for web.
And the best thing is that almost all the browsers support Base64; both encoding and decoding.
But first let's see few basics related to Base64.
What is Base64
Base64 is a binary ↭ text encoding-decoding scheme which means that you can represent/encode Binary data in form of text and vice versa.
Each character of Base64 is represented by exactly 6 bits. That's why we have 2^6 combinations which equates to 64 combinations of bits.
So the way any binary information can be represented as text is by representing a set of three binary characters each of 8 bits (octet) i.e. 24 bits to four 6 bit (sextet) Base64 characters.
Following illustration should explain the conversion:
Base64 Character Index Table:
Why base64 for web
Base64 will allow:
- To embed binary files inside the html/css files
- To deliver content in one go
- To reduce the network requests
- Combining multiple files into one
One of the biggest use cases of base 64 I have an ever encounter is embedding the images in css or html.
Another one is in the email, as in email if you have to deliver a newsletter and you cannot embed Files directly, Base64 is used and in some of the email providers you will see the original message in Base64 as well.
How to encode & decode Base64
Those functions are
btoa which allows conversion to and from respectively.
Let's take a look at an example of usage of these functions:
Here something to note and it will make easier to remember:
a in the function name means ASCII
b in the function name means Binary
atob: ASCII to Binary
btoa: Binary to ASCII
Though, these functions provide only way to convert strings.
To enable conversion of files, we will use
FileReader API. Following code example will demonstrate how to use
FireReader API to confer files to base64 string.
Following is the HTML to receive File(s) as input:
As you can see in the above example, we use the
FileReader API to get the data URL of the file. And as we know, the data URLs are mostly
base64 encoding of the file along with the information of how to interpret that data.
The Data URLs can contain other data encoding as well or may not even have any encoding. But the
readAsDataURL will always return with base64 encoding
Now you can accept multiple files in the html by adding
multiple attribute to the
file or by using Drag and Drop; you can read briefly about Drag and Drop here
Demo tool for Base64 Converter
So in this article, we saw how to generate Base64 inside the browser. Use these functions and tricks to generate Base64 in your applications and let us know how did it help you.
If you find this article helpful, please share it with others 🗣; subscribe to the blog for new posts and see you the next time.
Subscribe to Time to Hack
Get the latest posts delivered right to your inbox