javascript 附加 Blob 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15970729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:46:50  来源:igfitidea点击:

Appending Blob data

javascriptblob

提问by Deni Spasovski

Is there a function for appending blob data in JavaScriptI currently use the following approach:

JavaScript我目前使用以下方法是否有附加 blob 数据的功能:

var bb = new Blob(["Hello world, 2"], { type: "text/plain" });
bb = new Blob([bb, ",another data"], { type: "text/plain" });

And BlobBuilderfunction is not available in Chrome.

并且BlobBuilder功能在 Chrome 中不可用。

回答by nkron

Blobs are "immutable" so you can't change one after making it. Constructing a new Blob that appends the data to an existing blob (as you wrote in your initial question) is a good solution.

Blob是“不可变的”,所以你不能在创建后改变它。构建一个将数据附加到现有 Blob 的新 Blob(如您在最初的问题中所写)是一个很好的解决方案。

If you don't need to use the Blob each time you append a part, you can just track an array of parts. Then you can continually append to the array and then construct the Blob at the end when you need it.

如果您不需要在每次附加零件时都使用 Blob,您可以只跟踪零件数组。然后你可以不断地追加到数组,然后在你需要的时候在最后构造 Blob。

var MyBlobBuilder = function() {
  this.parts = [];
}

MyBlobBuilder.prototype.append = function(part) {
  this.parts.push(part);
  this.blob = undefined; // Invalidate the blob
};

MyBlobBuilder.prototype.getBlob = function() {
  if (!this.blob) {
    this.blob = new Blob(this.parts, { type: "text/plain" });
  }
  return this.blob;
};

var myBlobBuilder = new MyBlobBuilder();

myBlobBuilder.append("Hello world, 2");

// Other stuff ... 

myBlobBuilder.append(",another data");
var bb = myBlobBuilder.getBlob();