45

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

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

And BlobBuilder function is not available in Chrome.

Deni Spasovski
  • 4,004
  • 3
  • 35
  • 52
  • 2
    This is basically how you should do it, unless you can somehow keep the pieces of data in an array and then do a single Blob construction. – Ja͢ck Jul 22 '14 at 00:15
  • Thanks for the response Jack that's how I end up implementing it I just asked if there is a smarter solution and nkron just posted a nice one. – Deni Spasovski Jul 23 '14 at 02:44

1 Answers1

45

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.

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.

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();
nkron
  • 19,086
  • 3
  • 39
  • 27
  • The pdf file format is (mostly) text based so you could use something like this to build one. The format is very complex though so it's not as simple as combining two strings containing pdf data together to make a combined pdf. – nkron Sep 09 '20 at 06:12
  • 1
    I tried this solution for audio with MediaRecorder - it doesn't work - if using an array of blobs, and if flattening the blob array - it only uses one of them. – Yuval A. Sep 27 '20 at 12:17
  • @YuvalA. how do you solve it? I am facing the exact same issue (not using the above solution). I am trying to combinining the `BlobPart` but is only taking the last (or the first) `Blob`. – codenamezero Mar 02 '21 at 18:06
  • @codenamezero Are you able to solve it? I am trying to append two mediaRecorder Blobs. – rbansal Jun 12 '21 at 05:56
  • @rbansal I ended up just making a new `Blob`, I ran some test, as long as you don't create the new `Blob` too frequently, the performance hit is almost nothing. The system seems to be able to deal with it fairly well. Just put your Blobs into `BlobPart[]` and then pass it into `new Blob(yourBlobPartsArray)` – codenamezero Jun 15 '21 at 17:11