How can you encode a string to Base64 in JavaScript?

前端 未结 26 3820
梦如初夏
梦如初夏 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 05:08

    From the comments (by SET and Stefan Steiger) below the accepted answer, here is a quick summary of how to encode/decode a string to/from base64 without need of a library.

    str = "The quick brown fox jumps over the lazy dog";
    b64 = btoa(unescape(encodeURIComponent(str)));
    str = decodeURIComponent(escape(window.atob(b64)));
    

    Demo

    (uses jQuery library, but not for encode/decode)

    str = "The quick brown fox jumps over the lazy dog";
    
    $('input').val(str);
    
    $('#btnConv').click(function(){
      var txt = $('input').val();
      var b64 = btoa(unescape(encodeURIComponent(txt)));
      $('input').val(b64);
      $('#btnDeConv').show();
    });
    $('#btnDeConv').click(function(){
      var b64 = $('input').val();
      var txt = decodeURIComponent(escape(window.atob(b64)));
      $('input').val(txt);
    });
    #btnDeConv{display:none;}
    
    
    
    
    

提交回复
热议问题