Reputation: 1524
How to encode or decode a string in angular 2 with base64 ??? My front-end tool is Angular 2. I had a password string, before passing it to API I need to base64 encode. Since in service base64 encoded string will be decoded.
So I am looking for some base64 encode/decode library for Angular2/Typescript and some options.
Thanks!!!
Upvotes: 118
Views: 300413
Reputation: 1
onFileChange(event: any): void {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e: ProgressEvent<FileReader>) => {
if (e.target?.result) {
this.base64Image = e.target.result;
}
};
reader.readAsDataURL(file);
}
}
Upvotes: 0
Reputation: 332
From Angular 12 btoa()
and atob()
functions are deprecated. Use these instead:
console.log(Buffer.from("Hello World").toString('base64'));
// SGVsbG8gV29ybGQ=
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('binary'))
// Hello World
Note: you must explicit encoding!
Upvotes: 26
Reputation: 8440
For encoding to base64 in Angular2, you can use btoa() function.
Example:-
console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=
For decoding from base64 in Angular2, you can use atob() function.
Example:-
console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2
Upvotes: 5
Reputation: 17
Use btoa()
for encode and atob()
for decode
text_val:any="your encoding text";
Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0
Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text
Upvotes: 2
Reputation: 97152
Use the btoa()
function to encode:
console.log(btoa("password")); // cGFzc3dvcmQ=
To decode, you can use the atob()
function:
console.log(atob("cGFzc3dvcmQ=")); // password
Upvotes: 239
Reputation: 5782
Use btoa("yourstring")
more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs
Upvotes: 4