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?