二进制转base64

一. 以fetch的获取数据
1. response(后台返回): const buffer = response.arrayBuffer(),将二级制转成arrayBuffer类型

2. buffer转成base64 
function  arrayBufferToBase64 = buffer => {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i += 1) {
  binary += String.fromCharCode(bytes[i]);
}
  return window.btoa(binary);  //base64
};
3. url = `data:image/png;base64,${你的数据流}`
同事提供的建议,亲测有效

 

相关资源:

ArrayBuffer 对象用来表示通用的、固定长度的原始二进制数据缓冲区。
ArrayBuffer 不能直接操作,而是要通过类型数组对象或 DataView 对象来操作,
它们会将缓冲区中的数据表示为特定的格式,并通过这些格式来读写缓冲区的内容。

The Uint8Array typed array represents an array of 8-bit unsigned integers. 
The contents are initialized to 0. Once established, 
you can reference elements in the array using the object's methods, 
or using standard array index syntax (that is, using bracket notation).

fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。

btoa()  从 String 对象中创建一个 base-64 编码的 ASCII 字符串,
其中字符串中的每个字符都被视为一个二进制数据字节。

 

posted @ 2018-08-30 19:40  巫瞅瞅  阅读(14899)  评论(0编辑  收藏  举报