To convert a JavaScript Blob to a Firestore Blob you have to follow the steps below:
- Convert JavaScript Blob to ArrayBuffer using
your_blob.arrayBuffer()
.
- Wrap the ArrayBuffer you just got into a Uint8Array by passing it as the single parameter to the constructor.
- Use the
firebase.firestore.Blob.fromUint8Array(your_array)
method to, finally, create the Firestore Blob.
If you want to perform the inverse transformation, from Firestore Blob to JavaScript Blob, you have to, pretty much, do the opposite:
- Convert Firestore Blob to Uint8Array using
firestore_blob.toUint8Array()
.
- Create the JavaScript Blob using the constructor using the array. Keep in mind that you have to invoke it using a list of arrays, e.g.,
new Blob([my_array])
.
Here is an example of this in practice. The function save()
is used to, well, save the contents of the canvas to Firestore. And, the function load()
loads them into the canvas again.
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const db = firebase.firestore();
function save() {
canvas.toBlob(async blob => {
const blob_url = URL.createObjectURL(blob);
const ref = db.collection('blob').doc('blob');
const array_buffer = await blob.arrayBuffer();
const uint8_array = new Uint8Array(array_buffer);
const firebase_blob = firebase.firestore.Blob.fromUint8Array(uint8_array);
ref.update({
image: firebase_blob,
});
});
}
async function load() {
const ref = db.collection('blob').doc('blob');
const doc = await ref.get();
const firebase_blob = doc.get('image');
const uint8_array = firebase_blob.toUint8Array();
const blob = new Blob([uint8_array]);
const blob_url = URL.createObjectURL(blob);
const image = new Image();
image.onload = () => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0);
URL.revokeObjectURL(blob_url);
}
image.src = blob_url;
}