shlatchz shlatchz - 2 months ago 7
Javascript Question

Properly decode Get Blob data string to ArrayBuffer

I have the following code that receives blob's data from Azure Storage:

$.ajax({
headers: {
'x-ms-range': 'bytes=' + from + '-' + to,
'x-ms-version': '2015-07-08',
'x-ms-client-request-id': guid()
},
url: uri,
type: "GET",
success: function (data) {
/* data is a string! */
},
error: function (error, textStatus) { }
});


The call works fine and I receive the data in a textual form.
The problem is that I need to convert it to an
ArrayBuffer
.

Now I've tried lots of ways, such as:

new TextEncoder().encode(data);


and the following converter:

function stringToUint(string) {
var charList = string.split(''),
uintArray = [];
for (var i = 0; i < charList.length; i++) {
uintArray.push(charList[i].charCodeAt(0));
}
return new Uint16Array(uintArray);
}


But the data string isn't converted properly to binary (I've checked against the real binary value of the blob).

Should I use a different
ArrayBuffer
type? or am I using the wrong encoding (I've tried utf-8, utf-16, utf-32) when converting with the TextEncoder?

Please help :(

Answer

What finally worked for me was to use this jquery extension and change the request to:

$.ajax({
        headers: {
            'x-ms-range': 'bytes=' + from + '-' + to,
            'x-ms-version': '2015-07-08',
            'x-ms-client-request-id': guid()
        },
        url: uri,
        type: "GET",
        dataType: 'binary',
        responseType:'arraybuffer',
        processData: false,
        success: function (data) {
            /* data is an arraybuffer! */
        },
        error: function (error, textStatus) { }
});

Hopefully, it will help other people as well...

Comments