How can you encode a string to Base64 in JavaScript?

前端 未结 26 3809
梦如初夏
梦如初夏 2020-11-21 04:02

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

26条回答
  •  长情又很酷
    2020-11-21 04:57

    You can use window.btoa and window.atob...

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

    Probably using the way which MDN is can do your job the best... Also accepting unicode... using these two simple functions:

    // ucs-2 string to base64 encoded ascii
    function utoa(str) {
        return window.btoa(unescape(encodeURIComponent(str)));
    }
    // base64 encoded ascii to ucs-2 string
    function atou(str) {
        return decodeURIComponent(escape(window.atob(str)));
    }
    // Usage:
    utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
    atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
    
    utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
    atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
    

提交回复
热议问题