Skip to content

Fetch binary data over XHR and convert to base64 #24

@niloy

Description

@niloy

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 );
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions