到目前为止,我的文件阅读器 API 代码一直运行良好,直到有一天我从我的一位客户那里收到了一个 280MB 的 txt 文件。页面在 Chrome 中直接崩溃,而在 Firefox 中没有任何反应。
// create new reader object
var fileReader = new FileReader();
// read the file as text
fileReader.readAsText( $files[i] );
fileReader.onload = function(e)
{ // read all the information about the file
// do sanity checks here etc...
$timeout( function()
{
// var fileContent = e.target.result;
// get the first line
var firstLine = e.target.result.slice(0, e.target.result.indexOf("\n") ); }}
上面我想做的是获取第一个换行符,以便我可以获得文件的列长度。我不应该将其作为文本阅读吗?如何在不破坏大文件页面的情况下获取文件的列长度?
最佳答案
您的应用程序无法处理大文件,因为您在处理文件之前将整个文件读入内存。这种低效率可以通过流文件(读取较小的 block )来解决,因此您只需要将文件的一部分保存在内存中。
File
对象也是 Blob
的一个实例,它提供了 .slice
方法来创建文件的较小 View 。
这是一个假设输入为 ASCII 的示例(演示:http://jsfiddle.net/mw99v8d4/)。
function findColumnLength(file, callback) {
// 1 KB at a time, because we expect that the column will probably small.
var CHUNK_SIZE = 1024;
var offset = 0;
var fr = new FileReader();
fr.onload = function() {
var view = new Uint8Array(fr.result);
for (var i = 0; i < view.length; ++i) {
if (view[i] === 10 || view[i] === 13) {
// \n = 10 and \r = 13
// column length = offset + position of \r or \n
callback(offset + i);
return;
}
}
// \r or \n not found, continue seeking.
offset += CHUNK_SIZE;
seek();
};
fr.onerror = function() {
// Cannot read file... Do something, e.g. assume column size = 0.
callback(0);
};
seek();
function seek() {
if (offset >= file.size) {
// No \r or \n found. The column size is equal to the full
// file size
callback(file.size);
return;
}
var slice = file.slice(offset, offset + CHUNK_SIZE);
fr.readAsArrayBuffer(slice);
}
}
前面的代码片段计算换行符前的字节数。计算由多字节字符组成的文本中的字符数稍微困难一些,因为您必须考虑 block 中的最后一个字节可能是多字节字符的一部分的可能性。
关于javascript - 大文件的 filereader api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810051/