使用javascript将二进制数据转换为base64

时间:2012-06-11 15:03:11

标签: javascript html5 base64

HTML5使您能够在本地存储数据,我认为这很棒。例如,以下是如何使用它:

        var store = window.localStorage;
        store.setItem('foo', "hellow world");
        var test = store.getItem('foo');
        // test should = "hellow world"

在html中,您可以通过设置源来动态显示图像:

     "data:image/jpg;base64," + (base64string)

所以我的问题是如何将二进制数据转换为base64字符串,以便我可以利用html5本地存储?

例如,如果可以的话,那就太棒了:

$.ajax({
   url: 'someImage.png',
   type: 'POST',
   success: function (r) {

                // here I want to convert r to a base64 string !
                // r is not binary so maybe I have to use a different approach
                var data = ConvertToBase64(r);



                document.getElementById("img").src = "data:image/png;base64," + data;
            },
});

我知道我可以通过使用html5将图像包装在画布上然后将其转换为base64string来解决此问题。我也可以在服务器上发送一个特定的服务,它将发送该图像的base64字符串数据(someImage.aspx)。我只想知道是否可以从服务器检索二进制数据并将其转换为base64字符串。

6 个答案:

答案 0 :(得分:10)

要防止“InvalidCharacterError”错误,您需要执行以下操作:

var base64EncodedStr = btoa(unescape(encodeURIComponent(rawData)));

答案 1 :(得分:4)

使用FileReader将图像编码为数据网址:

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]));
});

答案 2 :(得分:2)

尝试btoa功能:

   var data = btoa(r);

答案 3 :(得分:1)

这是个老问题,但是找不到更好的答案,所以我写下了这个函数。它将Uint8Array直接转换为Base64,而无需将其转换为base64之前的字符串。希望它能对某人有所帮助。

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;
}

答案 4 :(得分:1)

//dataArr is a Uint8Array        
function toBase64(dataArr){
            return btoa(dataArr.reduce((data, val)=> {
                 return data + String.fromCharCode(val);
            }, ''));
        }

答案 5 :(得分:0)

适用于现代浏览器的公平而简单的解决方案

fetch('https://picsum.photos/536/354', {
    method: 'GET',
})
.then((data) => {
    // IMP to convert your json or other response to blob ( for this you have to check your api response is file / binary 
    return data.blob()
})
.then((data) => {
    var reader = new FileReader();
    reader.onload = function() {                         
        var b64 = reader.result
        console.log("This is base64", b64)
        document.getElementById("imagetoShow").src = b64
    }
    reader.readAsDataURL(data)
})
.catch((error) => {
    error.text().then( errorMessage => {
        console.log(errorMessage)
    })
})
<image src="" width="200" height="200" id="imagetoShow"/>