base64转化字节流 js_转换二进制数据使用JavaScript为Base64

本文探讨如何利用HTML5本地存储功能,将从服务器获取的二进制数据转换成Base64字符串,以便在HTML中显示图片。通过使用JavaScript的btoa函数,可以将二进制响应数据转换成Base64格式。
摘要由CSDN通过智能技术生成

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"

In html you can dynamically display an image by settig its source to:

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

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;

},

});

I know I could solve this problem by wrapping the image around a canvas using html5 then converting that to base64string. also I can make a specific service on the server that will send a base64 string data of that image (someImage.aspx).I just want to know if it will by possible to retrieve binary data from a server and convert that to a base64 string.

解决方案

Try the btoa function:

var data = btoa(r);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值