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 ..
Advertisement
Answer
I managed to achieved this, and it might not be the suitable way, but I’m posting it here in case someone else might find it useful.
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; I had to add processData: false , otherwise, passing the array will be processed, and in my case, the service failed to de-serialize 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