JavaScript Base64 Decode
To convert Base64 to original data, JavaScript provides the atob
function which is an acronym for “ASCII to Binary”. In JavaScript Base64 values are obtained using the btoa function.
Usage:
atob(data)
- Convertsdata
toSTRING
and decodes it from Base64
Arguments:
data
(required string) - The Base64 value you want to decode
Return Values:
STRING
- On success, it returns the original data (it can be either text or binary)
Exceptions:
On failure the function may throw one of the following exceptions:
InvalidCharacterError
: String contains an invalid characterTypeError
: Not enough arguments to Window.atob
Example #1 (basic usage):
var str = atob('Z3VydQ==');
console.log(str); //-> "guru"
Example #2 (check if function is supported):
if (typeof atob !== 'function') {
// Cannot decode Base64 values because the atob() function is not supported
// Perhaps you want to use a polyfill or at least inform user about this
}
Example #3 (non-string data):
// Before decoding Base64 values the btoa() function converts it to String()
// It is for this reason that you will not get any errors if you pass a “wrong” data type
// For example, that is why in the example below you will get the same results
atob(null); //-> "�ée"
atob('null'); //-> "�ée"
Example #4 (unicode string):
// By default most browsers don’t support Unicode strings
// For example, this is why the btoa() function will fail to encode “€100” to Base64
// However, the atob() function doesn’t fail to decode “4oKsMTAw” (real Base64 value of the “€100”)
// In fairness, you get a completely different result, because string is treated as ASCII
var b64 = '4oKsMTAw',
data = atob(b64);
console.log(data); //-> "�100"
For more info, check the following examples:
Comments (25)
I hope you enjoy this discussion. In any case, I ask you to join it.
<a href="data:application/pdf;base64,YOUR_B64_STRING" download="file.pdf">file.pdf</a>
`https://stackoverflow.com/questions/48836541/save-binary-file-from-base64-data-in-javascript`