Convert binary data to base64 with javascript

前端 未结 4 969
遥遥无期
遥遥无期 2020-11-27 07:54

HTML5 enable you to store data locally which I think it is great. For example here is how you can use it:

        var store = window.localStorage;
        st         


        
相关标签:
4条回答
  • 2020-11-27 07:58

    Use a FileReader to encode your image as a data URL:

    jQuery.ajax({...})
    .done(function (r) {
      var reader = new FileReader(
      reader.onload = (function(self) {
        return function(e) {
          document.getElementById("img").src = e.target.result;
        }
      })(this);
      reader.readAsDataURL(new Blob([r]));
    });
    
    0 讨论(0)
  • 2020-11-27 07:59

    Try the btoa function:

       var data = btoa(r);
    
    0 讨论(0)
  • 2020-11-27 08:09

    To prevent 'InvalidCharacterError' error, you need to do this:

    var base64EncodedStr = btoa(unescape(encodeURIComponent(rawData)));
    
    0 讨论(0)
  • 2020-11-27 08:10

    This is old question, but could not find a better answer, so I wrote down this function. It will convert the Uint8Array directly to Base64 without converting it into a string before base64. Hope it will help someone.

    var encoder = new TextEncoder("ascii");
    var decoder = new TextDecoder("ascii");
    var base64Table = encoder.encode('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=');
    function toBase64(dataArr){
        var padding = dataArr.byteLength % 3;
        var len = dataArr.byteLength - padding;
        padding = padding > 0 ? (3 - padding) : 0;
        var outputLen = ((len/3) * 4) + (padding > 0 ? 4 : 0);
        var output = new Uint8Array(outputLen);
        var outputCtr = 0;
        for(var i=0; i<len; i+=3){              
            var buffer = ((dataArr[i] & 0xFF) << 16) | ((dataArr[i+1] & 0xFF) << 8) | (dataArr[i+2] & 0xFF);
            output[outputCtr++] = base64Table[buffer >> 18];
            output[outputCtr++] = base64Table[(buffer >> 12) & 0x3F];
            output[outputCtr++] = base64Table[(buffer >> 6) & 0x3F];
            output[outputCtr++] = base64Table[buffer & 0x3F];
        }
        if (padding == 1) {
            var buffer = ((dataArr[len] & 0xFF) << 8) | (dataArr[len+1] & 0xFF);
            output[outputCtr++] = base64Table[buffer >> 10];
            output[outputCtr++] = base64Table[(buffer >> 4) & 0x3F];
            output[outputCtr++] = base64Table[(buffer << 2) & 0x3F];
            output[outputCtr++] = base64Table[64];
        } else if (padding == 2) {
            var buffer = dataArr[len] & 0xFF;
            output[outputCtr++] = base64Table[buffer >> 2];
            output[outputCtr++] = base64Table[(buffer << 4) & 0x3F];
            output[outputCtr++] = base64Table[64];
            output[outputCtr++] = base64Table[64];
        }
        
        var ret = decoder.decode(output);
        output = null;
        dataArr = null;
        return ret;
    }
    
    0 讨论(0)
提交回复
热议问题