How can you encode a string to Base64 in JavaScript?

前端 未结 26 3881
梦如初夏
梦如初夏 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:49

    This question and it's answers pointed me to the right direction.
    Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..

    Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)

    function b64EncodeUnicode(str) {
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
            return String.fromCharCode('0x' + p1);
        }));
    }
    
    b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
    b64EncodeUnicode('\n'); // "Cg=="
    
    
    
    function b64DecodeUnicode(str) {
        return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
    
    b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
    b64DecodeUnicode('Cg=='); // "\n"
    

    These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.

    If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.

提交回复
热议问题