JavaScript

Encode/Decode text & files to Base64 in Browser with Base64 Converter

Encode/Decode text & files to Base64 in Browser with Base64 Converter

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:

Index Char Index Char Index Char Index Char
0 A 16 Q 32 g 48 w
1 B 17 R 33 h 49 x
2 C 18 S 34 i 50 y
3 D 19 T 35 j 51 z
4 E 20 U 36 k 52 0
5 F 21 V 37 l 53 1
6 G 22 W 38 m 54 2
7 H 23 X 39 n 55 3
8 I 24 Y 40 o 56 4
9 J 25 Z 41 p 57 5
10 K 26 a 42 q 58 6
11 L 27 b 43 r 59 7
12 M 28 c 44 s 60 8
13 N 29 d 45 t 61 9
14 O 30 e 46 u 62 +
15 P 31 f 47 v 63 /

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

JavaScript provides two functions which allow conversion to and from base64.

Those functions are atob and btoa which allows conversion to and from respectively.

Let's take a look at an example of usage of these functions:

const name = 'Time to Hack';

const encodedName = btoa(name);

console.log(encodedName);
// outputs: VGltZSB0byBIYWNr
encoding name to base64
encoding name to base64
const encodedName = 'VGltZSB0byBIYWNr';

const name = atob(name);

console.log(name);
// outputs: Time to Hack
encoding name from base64
encoding name from base64

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

So:
- atob: ASCII to Binary
- btoa: Binary to ASCII

Why?

The thread on this StackOverflow questions explains it;
TL;DR: jump to answers [naming reason] and [how it ended up named like this]


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:

<div class="row">
  <form class="col-4" name="file-upload">
    <div class="form-group">
      <label>File</label>
      <input type="file" class="form-control" name="myFile" id="myFile" />
    </div>
    <button 
      type="button" id="getBase64"
      class="btn btn-primary">Generate Base64</button>
  </form>
  <div class="col-8">
    <div class="form-group">
      <label>Base64 of File</label>
      <textarea
        class="form-control" rows="5"
        id="base64ofFile"
        placeholder="Base64 will appear here"
        ></textarea>
    </div>
  </div>
</div>
HTML to take the File Input for Base64 string
// code to use FileReader to get base64 of files
const getBase64OfFile = (file, callback) => {
  const fr = new FileReader();
  fr.addEventListener('load', (e) => {
    if(typeof callback === 'function') {
      callback(fr.result.split('base64,')[1]);
    }
  });
  fr.readAsDataURL(file);
}

document.addEventListener('DOMContentLoaded', () => {
  const op = document.querySelector('#base64ofFile');
  const btn = document.querySelector('#getBase64');
  const fileInput = document.querySelector('#myFile');

  btn && btn.addEventListener('click', () => {
    const file = fileInput.files[0];
    file && getBase64OfFile(file, (data) => {
      op.innerText = data;
    });
  })
});
JS with FileReader API to get base64 of files

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 FireReader API's readAsDataURL will always return with base64 encoding

Now you can accept multiple files in the html by adding multiple attribute to the input type file or by using Drag and Drop; you can read briefly about Drag and Drop here


Demo tool for Base64 Converter


Conclusion

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.

Let me know what do you think about this article through comments 💬 or on Twitter at @patel_pankaj_ and @time2hack

If you find this article helpful, please share it with others 🗣; subscribe to the blog for new posts and see you the next time.


Credits

You've successfully subscribed to Time to Hack!