I have the following resource:
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);
}
var API = $resource(server + 'album', {}, {
get: {
url: server + 'album/:albumId/photo/:photoId',
method: 'GET',
responseType: 'arraybuffer',
headers: {
'AuthToken': 'the secret',
'Accept': 'image/*'
},
interceptor: {
response: function(resp) {
return 'data:'+ resp.headers('Content-Type') + ';base64,' + _arrayBufferToBase64(resp.data)};
}
}
}
});
what it does is to receive the binary content of the file from server and return a data uri with the base64 data inside.
I have to say that this call can not be replaced with a simple src tag to the url as there are some authentication headers sent too.
this works fine in newer browsers but I want to keep compatibility with older browsers, so the arraybuffer is a problem here, my question is: is there a way to do all these without arraybuffer?
I tried to remove the response type and convert the string in resp.data using what is described here but no success.
Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”. Uint16Array – treats every 2 bytes as an integer, with possible values from 0 to 65535.
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".
An ArrayBuffer is in the memory, available for manipulation. A Blob can be on disk, in cache memory, and other places not readily available. But the data from a Blob can be copied into an ArrayBuffer.
Sending binary dataThe send method of the XMLHttpRequest has been extended to enable easy transmission of binary data by accepting an ArrayBuffer , Blob , or File object. The following example creates a text file on-the-fly and uses the POST method to send the "file" to the server.
Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding. I haven't tested them, but there are a number of algorithms for converting between arrays of bytes and base64 URI's. In particular the base64EncArray
function seems to be what you are looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With