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
JavaScript
x
18
18
1
var xhr = new XMLHttpRequest;
2
xhr.responseType = 'blob';
3
4
xhr.onload = function() {
5
var recoveredBlob = xhr.response;
6
var reader = new FileReader;
7
8
reader.onload = function() {
9
var blobAsDataUrl = reader.result;
10
return blobAsDataUrl.toString().replace('data:image/png;base64,', '');
11
};
12
reader.readAsDataURL(recoveredBlob);
13
};
14
15
xhr.open('GET', blobUrl);
16
xhr.send();
17
18
Then used following to convert it to an array
JavaScript
1
5
1
var bData = atob(blob);
2
console.log('------ bData : ', bData);
3
const array = Uint8Array.from(bData, b => b.charCodeAt(0));
4
5
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
JavaScript
1
19
19
1
var xhr = new XMLHttpRequest;
2
xhr.responseType = 'blob';
3
4
xhr.onload = function() {
5
var recoveredBlob = xhr.response;
6
const reader = new FileReader();
7
// This fires after the blob has been read/loaded.
8
reader.addEventListener('loadend', (e) => {
9
blob = new Uint8Array(e.target.result);
10
// calling the save method
11
});
12
// Start reading the blob as text.
13
reader.readAsArrayBuffer(recoveredBlob);
14
};
15
// get the blob through blob url
16
xhr.open('GET', blobUrl_);
17
xhr.send();
18
19
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.
JavaScript
1
16
16
1
$.ajax({
2
type: 'PATCH',
3
url: url_,
4
contentType: 'application/octet-stream',
5
data: blob,
6
processData: false,
7
headers: {
8
"If-Match": newEtag,
9
"X-XSRF-TOKEN": xsrfSessionCookie,
10
},
11
success: function (res) {
12
// do something
13
}
14
});
15
16
Cheers