1

I am experimenting to see if I can customize a Blob that I will pass to a FileReader. The goal of the sample code is to be able to programmatically generate data on the fly for the FileReader to consume. However, it looks like I am not subclassing correctly as I get a TypeError when I try to use my custom class.

Here is my sample code:

// Example of reading a real blob
var realBlob = new Blob(['foo', 'bar']);
var reader1 = new FileReader();
reader1.onload = function(event){
    console.log(JSON.stringify(reader1.result));
};
reader1.readAsText(realBlob);
// Writes "foobar"

// (non-working) streaming blob
function StreamingBlob() {}
StreamingBlob.prototype = new Blob;
StreamingBlob.prototype.constructor = StreamingBlob;
var bInst = new StreamingBlob();

bInst.slice = function (start, end) {
    str = '';
    while (start++ < end) {
        str += 'A';
    }
    return new Blob([str]);
}

// Instance of says it's a Blob
console.log(bInst instanceof StreamingBlob);
console.log(bInst instanceof Blob);

console.log(bInst);
console.log(bInst.slice(1,5));

var reader2 = new FileReader();
reader2.onload = function(event){
    console.log(JSON.stringify(reader2.result));
};
reader2.readAsText(bInst);
// Error!

When I run this I see:

true
true
StreamingBlob {slice: function, type: "", size: 0, constructor: function}
Blob {type: "", size: 4, slice: function}
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
"foobar"

I'm confused, because the instanceof check claims that my object is a Blob, but the readAsText method generates an error that claims otherwise.

Is there a better way to do this?

TimeMalt
  • 347
  • 4
  • 6
  • If at all, try [correct inheritance](http://stackoverflow.com/a/10898859/1048572). But I don't think `Blob` is subclassable, it's a native interface. – Bergi Feb 02 '15 at 09:25
  • Look like that doesn't work either. http://jsfiddle.net/0s2th8n5/ , I'll see if there is another way to get what I want. Thanks! – TimeMalt Feb 03 '15 at 08:02
  • You'd probably have to make a new file-reader that can read your blobs and the old blobs and replace the old one with it. – Rick Jun 16 '15 at 20:49
  • Are there any updates on subclassing blob? Or a way to implement blob interface from scratch? I have a slice function but it says I still don't implement the blob interface.. – Colin D Dec 22 '17 at 20:36
  • I ended up abandoning this, so I don't know a way to do it. :( – TimeMalt Dec 03 '19 at 14:09

0 Answers0