26

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 字符串。

4

6 回答 6

20

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

var base64EncodedStr = btoa(unescape(encodeURIComponent(rawData)));
于 2017-01-03T13:51:45.090 回答
11

使用FileReader将图像编码为数据 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]));
});
于 2015-03-12T10:05:34.390 回答
6

试试这个btoa功能:

   var data = btoa(r);
于 2012-06-11T15:04:48.957 回答
5

这是一个老问题,但找不到更好的答案,所以我写下了这个函数。它会将 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;
}
于 2020-08-21T16:40:58.170 回答
2
//dataArr is a Uint8Array        
function toBase64(dataArr){
            return btoa(dataArr.reduce((data, val)=> {
                 return data + String.fromCharCode(val);
            }, ''));
        }
于 2021-05-06T20:43:41.937 回答
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"/>

于 2021-06-29T03:13:44.663 回答