python base64 encode string code example

Example 1: base64 encode python

import base64

message = "Python is fun"
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')

print(base64_message)

Example 2: decode base64 python

import base64
msg = base64.b64decode(msg)

Example 3: base64 decode python

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

Example 4: javascript base64 encode file input

var fileInput = document.getElementById('#myInputID');

var reader = new FileReader();
reader.readAsDataURL(fileInput.files[0]);

reader.onload = function () {
	console.log(reader.result);//base64encoded string
};
reader.onerror = function (error) {
	console.log('Error: ', error);
};

Example 5: javascript encode base64

const encoded = window.btoa('Alireza Dezfoolian'); // encode a string
const decoded = window.atob(encoded); // decode the string

Example 6: base64 python decode

import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)