Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a blob in javascript

Tags:

javascript

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.

like image 689
ncohen Avatar asked Dec 11 '22 16:12

ncohen


2 Answers

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});
like image 199
Felix Kling Avatar answered Dec 13 '22 04:12

Felix Kling


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:

  1. User uploads a file
  2. You receive the file, clone it, possibly display it to the user to show you really have it
  3. User deletes, renames, or moves the original file
  4. 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();
  });
});
like image 39
twhb Avatar answered Dec 13 '22 04:12

twhb