使用javascript将二进制数据转换为base64 [英] Convert binary data to base64 with javascript

查看:101
本文介绍了使用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);

这篇关于使用javascript将二进制数据转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆