How to convert blob url to a byte array using javascript only

Tags: ,



I have blob url , i need to get it converted into a byte [] for storing purpose . I initially tried converting it to a base64 using FileReader

    var xhr = new XMLHttpRequest;
    xhr.responseType = 'blob';

    xhr.onload = function() {
        var recoveredBlob = xhr.response;
        var reader = new FileReader;

        reader.onload = function() {
            var blobAsDataUrl = reader.result;
            return blobAsDataUrl.toString().replace('data:image/png;base64,', '');
        };
        reader.readAsDataURL(recoveredBlob);
    };

    xhr.open('GET', blobUrl);
    xhr.send(); 

Then used following to convert it to an array

var bData = atob(blob);
console.log('------ bData : ', bData);
const array = Uint8Array.from(bData, b => b.charCodeAt(0));

But I do not get the intended binary output ..

Answer

So I managed to achieved this and it might not be the suitable way but posting here as if someone else might find it useful.

So what I have is a blob url, and

var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';

xhr.onload = function() {
    var recoveredBlob = xhr.response;
    const reader = new FileReader();
    // This fires after the blob has been read/loaded.
    reader.addEventListener('loadend', (e) => {
        blob =  new Uint8Array(e.target.result);
        // calling the save method
    });
    // Start reading the blob as text.
    reader.readAsArrayBuffer(recoveredBlob);
};
// get the blob through blob url 
xhr.open('GET', blobUrl_);
xhr.send();

Also I had to do a modification to my jquery service call , had to add processData: false , otherwise passing array will be processed and in my case the service failed to desterilize it.

$.ajax({
    type: 'PATCH',
    url: url_,
    contentType: 'application/octet-stream',   
    data: blob,
    processData: false,
    headers: {
        "If-Match": newEtag,
        "X-XSRF-TOKEN": xsrfSessionCookie,
    },
    success: function (res) {
        // do something 
    } 
});

Cheers



Source: stackoverflow