How can you encode a string to Base64 in JavaScript?

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

    Please note that this is not suitable for raw Unicode strings! See Unicode section here.

    Syntax for encoding

    var encodedData = window.btoa(stringToEncode);

    Syntax for decoding

    var decodedData = window.atob(encodedData);

    0 讨论(0)
  • 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!"
    
    0 讨论(0)
  • 2020-11-21 04:59

    Here is a LIVE DEMO of atob() and btoa() JS built in functions:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          textarea{
            width:30%;
            height:100px;
          }
        </style>
        <script>
          // encode string to base64
          function encode()
          {
            var txt = document.getElementById("txt1").value;
            var result = btoa(txt);
            document.getElementById("txt2").value = result;
          }
          // decode base64 back to original string
          function decode()
          {
            var txt = document.getElementById("txt3").value;
            var result = atob(txt);
            document.getElementById("txt4").value = result;
          }
        </script>
      </head>
      <body>
        <div>
          <textarea id="txt1">Some text to decode
          </textarea>
        </div>
        <div>
          <input type="button" id="btnencode" value="Encode" onClick="encode()"/>
        </div>
        <div>
          <textarea id="txt2">
          </textarea>
        </div>
        <br/>
        <div>
          <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
          </textarea>
        </div>
        <div>
          <input type="button" id="btndecode" value="Decode" onClick="decode()"/>
        </div>
        <div>
          <textarea id="txt4">
          </textarea>
        </div>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-11-21 05:00

    You can use btoa (to base-64) and atob (from base-64).

    For IE 9 and below, try the jquery-base64 plugin:

    $.base64.encode("this is a test");
    $.base64.decode("dGhpcyBpcyBhIHRlc3Q=");
    
    0 讨论(0)
  • 2020-11-21 05:03

    Use js-base64 library as

    btoa() doesn't work with emojis

    var str = "I was funny                                                                     
    0 讨论(0)
  • 2020-11-21 05:04

    For my project I still need to support IE7 and work with large input to encode.

    Based on the code proposed by Joe Dyndale and as suggested in comment by Marius, it is possible to improve the performance with IE7 by constructing the result with an array instead of a string.

    Here is the example for encode:

    var encode = function (input) {
        var output = [], chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
    
        input = _utf8_encode(input);
    
        while (i < input.length) {
    
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
    
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
    
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
    
            output.push(_keyStr.charAt(enc1));
            output.push(_keyStr.charAt(enc2));
            output.push(_keyStr.charAt(enc3));
            output.push(_keyStr.charAt(enc4));
    
        }
    
        return output.join("");
    };
    
    0 讨论(0)
提交回复
热议问题