I'm desperately trying to clone a blob in javascript without using an external library (such as jQuery).
I've tried JSON.parse(JSON.stringify(blob))
without success.
From the documentation:
To create a blob that contains a subset of another blob's data, use the
slice()
method.
So you could probably use
var copy = blob.slice();
It also says
To construct a Blob from other non-blob objects and data, use the Blob() constructor.
and looking at the constructors documentation's suggests that the following should work as well:
var copy = new Blob([blob], {type: blob.type});
Note that the accepted answer doesn’t clone the underlying data, it creates another reference to it. So does new Blob([myBlob])
. This is usually what you want, because it avoids creating extra copies of the file in memory, which can be expensive at common filesizes. However, since File
objects also are references not copies, this results in behavior like the following:
To avoid this, you need to actually clone the underlying data, which you can do with this function.
const cloneBlob = b => new Promise((resolve, reject) => {
const r = new FileReader();
r.readAsArrayBuffer(b);
r.addEventListener('load', _ => {
resolve(new Blob([r.result], {type: b.type}));
});
r.addEventListener('error', _ => {
reject();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With