[英]How to clone a blob in javascript
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
对象也是引用而不是副本,这会导致如下行为:
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.