使用javascript将二进制数据转换为base64
HTML5 使您能够在本地存储数据,我认为这很棒.例如,您可以使用它:
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;
store.setItem('foo', "hellow world");
var test = store.getItem('foo');
// test should = "hellow world"
在 html 中,您可以通过将其来源设置为动态显示图像:
In html you can dynamically display an image by settig its source to:
"data:image/jpg;base64," + (base64string)
所以我的问题是如何将二进制数据转换为 base64 字符串,以便利用 html5 本地存储?
So my question is how can I convert binary data to a base64 string so that I can take advantage of html5 local storage?
例如,如果可以的话,那就太好了:
For example it will be great if I could:
$.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 字符串.
推荐答案
试试 btoa
功能:
Try the btoa
function:
var data = btoa(r);
相关文章