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.
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.
- Please elaborate on "blob". – Felix Kling Commented Jun 14, 2016 at 2:27
- 1 Did you try what is suggested in the docs you linked to? "To create a blob that contains a subset of another blob's data, use the slice() method" – Felix Kling Commented Jun 14, 2016 at 2:29
- @FelixKling I've added a link to the blob word. In my case the blob is a pdf but I don't think it has an influence on the question... – Nate Commented Jun 14, 2016 at 2:30
2 Answers
Reset to default 18From 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 mon filesizes. However, since File
objects also are references not copies, this results in behavior like the following:
- User uploads a file
- You receive the file, clone it, possibly display it to the user to show you really have it
- User deletes, renames, or moves the original file
- Your copy of the file vanishes
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();
});
});