简体   繁体   English

如何在javascript中克隆一个blob

[英]How to clone a blob in javascript

I'm desperately trying to clone a blob in javascript without using an external library (such as jQuery).我拼命地尝试在不使用外部库(例如 jQuery)的情况下在 javascript 中克隆一个blob

I've tried JSON.parse(JSON.stringify(blob)) without success.我试过JSON.parse(JSON.stringify(blob))没有成功。

From the documentation:从文档:

To create a blob that contains a subset of another blob's data, use the slice() method.要创建包含另一个 blob 数据子集的 blob,请使用slice()方法。

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.要从其他非 Blob 对象和数据构造 Blob,请使用 Blob() 构造函数。

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]) . 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:但是,由于File对象也是引用而不是副本,这会导致如下行为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM