二進制轉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 字符串,
其中字符串中的每一個字符都被視爲一個二進制數據字節。