7

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.

2
  • 1
    You might want to check this related question. Some of the answer there might help you get to a solution. stackoverflow.com/questions/20617720/… Commented Feb 24, 2014 at 23:33
  • 1
    you can store binary in a string of you handle the unicode conversion by bit-shifting each char in a loop, much like you use to pack the AB. google "binary ajax" and look for old examples. Commented Feb 25, 2014 at 17:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.