6

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.

3
  • Please elaborate on "blob". 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" 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... Commented Jun 14, 2016 at 2:30

2 Answers 2

18

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});
Sign up to request clarification or add additional context in comments.

Comments

3

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();
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.