Is there a way to stream data into a blob (or generate a giant blob)

前端 未结 1 1652
长情又很酷
长情又很酷 2021-01-19 06:57

Checking MDN I see there used to be BlobBuilder and that I could call blobBuilder.append to continue adding data to a blob but according to MDN BlobBuilder is d

相关标签:
1条回答
  • 2021-01-19 07:38

    As you know, the data that the blob will contain must be ready to pass to the constructor. Let us take the example from MDN:

    var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
    var oMyBlob = new Blob(aFileParts, {type : 'text/html'});
    

    Now, we have two options:

    1. We can append data to the array, and then convert it to a blob:

      var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
      aFileParts.push('<p>How are you?</p>');
      var oMyBlob = new Blob(aFileParts, {type : 'text/html'});
      
    2. Alternatively, we can use blobs to create the blob:

      var oMyOtherBlob = new Blob([], {type: 'text/html'});
      oMyOtherBlob = new Blob([oMyOtherBlob, '<a id="a"><b id="b">hey!</b></a>'], {type : 'text/html'});
      oMyOtherBlob= new Blob([oMyOtherBlob, '<p>How are you?</p>'], {type : 'text/html'});
      

    You may build your own BlobBuilder encapsulating that... given that appending to an array seems to lead you to run out of memory, let us encapsulate the second option:

    var MyBlobBuilder = function() {
         var blob = new Blob([], {type: 'text/html'});
         this.append = function(src)
         {
             blob = new Blob([blob, src], {type: 'text/html'});
         };
         this.getBlob = function()
         {
             return blob;
         }
    };
    

    Note: tested with your code (replaced BlobBuilder with MyBlobBuilder), did not run out of memory on my machine. Windows 10, Chrome 67, 8 GB Ram, Intel Core I3 - 64 bits.

    0 讨论(0)
提交回复
热议问题