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.
Here is a sample code to begin with.
<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.
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.
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.
Define Upload Process Function
Let's create a function called
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.
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.
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.