JavaScript Base64 Encoding and Decoding
Browsers provide btoa() and atob(), but these functions operate on byte-like strings. Passing Chinese text or emoji directly can throw an error or corrupt characters.
Use UTF-8 bytes
Convert text with TextEncoder before encoding and TextDecoder after decoding. This preserves multilingual form data.
const bytes=new TextEncoder().encode(text); const encoded=btoa(String.fromCodePoint(...bytes)); const decoded=new TextDecoder().decode(Uint8Array.from(atob(encoded),c=>c.charCodeAt(0)));Handling files
Use FileReader for small previews or process ArrayBuffer chunks for larger files. Avoid building huge intermediate strings. Try the online encoder.