niloy / blog

blog raw files
3 stars 1 forks source link

Fetch binary data over XHR and convert to base64 #24

Open niloy opened 9 years ago

niloy commented 9 years ago

To fetch binary data and convert to base64, do the following:

Fetch binary data by set responseType = "arraybuffer" for XHR. Make sure to read response and NOT responseText.

After you have the response, I thought simply using btoa(response) will do the base64 conversion. But it does not work.

Instead, a custom function needs to be used for reason I don't know. Below is the function taken from here:

  function arrayBufferToBase64(buffer) {
    var binary = "";
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
  }