最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to clone a blob in javascript - Stack Overflow

programmeradmin9浏览0评论

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.

Share Improve this question edited Jun 14, 2016 at 2:28 Nate asked Jun 14, 2016 at 2:26 NateNate 7,86623 gold badges75 silver badges129 bronze badges 3
  • 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
Add a ment  | 

2 Answers 2

Reset to default 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});

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:

  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();
  });
});
发布评论

评论列表(0)

  1. 暂无评论