从本地文件读取混合类型
我正在尝试使用 Javascript 读取混合有整数、浮点数和字符串的文件类型。
然后使用 File API 拖放该文件,将其作为数组缓冲区读取并用 DataView
包装。这可以处理数字类型,但我必须制定自己的方法来获取文本。
DataView.prototype.getAscii = function(byteOffset, byteLength)
{
var bytes = new Array(byteLength);
for (var i = 0; i < byteLength; i++) {
bytes[i] = this.getUint8(byteOffset + i);
}
return String.fromCharCode.apply(null, bytes);
}
它工作得很好,但我担心读取大文件的单个字节的速度。类型化数组据说可以与普通数组互换使用,所以我尝试了这个:
DataView.prototype.getAscii = function(byteOffset, byteLength)
{
var bytes = new Uint8Array(this.buffer, byteOffset, byteLength);
return String.fromCharCode.apply(null, bytes);
}
我收到一条“TypeError: Function.prototype.apply: Arguments list has bad type”消息,所以它不像我的 Uint8Array
那样一个参数。
有没有更好的方法一次读取多个字符? FileReader#readAsText()
读取整个文件,但不允许访问任何二进制方法。
I am trying to read a file type that has a mixture of integers, floats and strings using Javascript.
The file is drag-dropped then, with the File API, read as array buffer and wrapped with a DataView
. That takes care of the number types but I had to make my own method for getting text.
DataView.prototype.getAscii = function(byteOffset, byteLength)
{
var bytes = new Array(byteLength);
for (var i = 0; i < byteLength; i++) {
bytes[i] = this.getUint8(byteOffset + i);
}
return String.fromCharCode.apply(null, bytes);
}
It works well enough but I worry about the speed of reading individual bytes for large files. Typed arrays can supposedly be used interchangeably with normal arrays so I tried this:
DataView.prototype.getAscii = function(byteOffset, byteLength)
{
var bytes = new Uint8Array(this.buffer, byteOffset, byteLength);
return String.fromCharCode.apply(null, bytes);
}
I get a "TypeError: Function.prototype.apply: Arguments list has wrong type" message so it doesn't like my Uint8Array
as a parameter.
Is there a better way of reading many characters at once? FileReader#readAsText()
reads the whole file but doesn't give access to any of the binary methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 .webkitSlice/.mozSlice 对文件进行切片,然后对不同的范围使用 readAsText 和 readAsArrayBuffer 。
You could slice your file with .webkitSlice/.mozSlice and then use readAsText and readAsArrayBuffer for different ranges.