circuit

Base64 Encoding in JavaScript

Including upload an image using base64 in JavaScript




Image of lots of padlocks

Base64 is basically a way to encode information and it's typically used when you want to send binary data over a text-based protocol such as HTTP. You can also use it to ensure your text or information does not get corrupted during a transfer. For example, you can submit an HTML form using base64 as the encoding type. It is not a way to conceal information or data. Means that you should use it as a method of security by itself because you can easily convert a base64 string back to its original form in any programming language.

Get Started

Here is a sample code to begin with.

Sample Code

Let's first define base64 string within JavaScript.

<script>
   const str = "Hello world!";
   const base64 = btoa(str);
   const decode = atob(base64); console.log("Original: " + str);
   console.log("Base64: " + base64);
   console.log("Decoded: " + decode);
</script>

btoa() function encodes the content to base64.

atob() function decodes the base64 string into its original form.

Result

Result

Here we have 3 strings - Original, Base64 and Decoded accordingly. This is the basics of encoding and decoding base64 in JavaScript.

Let's see how we can actually use base64 by uploading an HTML canvas image to the server.

Upload Image using Base64

Create a blank folder named image and a php file called upload.php.

Upload.php

Upload.php

We're going to post the image to this file which is going to decode the JSON body. Then, save the image inside the image directory and the image name is taken from the current UNIX timestamp dot png.

Next, create a new canvas element and upload button.

Create a canvas and button.

Now let's do some basic drawing on this canvas to get some contents.

Here we get a reference for both canvas and the button. Then we get the canvas 2d rendering context. This is a way we can draw on the actual canvas.

We start by putting a light grey for the background of the canvas and then set the width and height of the canvas. To make it more interesting, we put a text on it.

Result

Define Upload Process Function

Let's create a function called uploadCanvasImage.

The function will trigger when the upload button is clicked. First, we're going to get the base64 string of the actual canvas by using toDataURL method.

Result

We'll get the data as above. Starting after the comma is the base64 representation of the canvas. So we need to split the string on the comma and we can only take the data inside index 1.

Then, we create a constant called body which will be what's going to be sent through as JSON. After that, we make a request to the upload.php file.

Final Result

We can see inside the network tab that we have successfully posted across all of the base64 string to the server.

And inside the image folder, we have a standard PNG file of the canvas.




Continue Learning