我正在尝试查看是否可以自定义我将传递给FileReader的Blob。示例代码的目标是能够以编程方式 动态生成数据以供FileReader使用。但是,当我尝试使用自定义类时,看起来我没有正确地进行子类化,因为我得到了一个TypeError。
以下是我的示例代码:
// 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!
当我跑步时,我看到:
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"
我感到困惑,因为检查的instanceof声称我的对象是Blob,但readAsText方法会生成一个错误声明,否则就会声称。
有更好的方法吗?