javascriptbase64binaryfiles

How can you encode/decode a string to Base64 in JavaScript?


I have a PHP script that can encode a PNG image to a Base64 string.

I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.


Solution

  • You can use btoa() and atob() to convert to and from base64 encoding.

    There appears to be some confusion in the comments regarding what these functions accept/return, so…

    See also:


    Most comments here are outdated. You can probably use both btoa() and atob(), unless you support really outdated browsers.

    Check here: