您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

大文件上的filereader API

大文件上的filereader API

您的应用程序无法处理大文件,因为您在处理之前将整个文件读入内存。这种低效率可以通过流式传输文件(读取小块)来解决,因此您只需要在内存中保留文件的一部分即可。

File对象也是一个实例Blob,它提供了.slice创建文件的较小视图的方法

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);
    }
}

一个代码段计算换行之前的字节数。计算由多字节字符组成的文本中的字符数稍微困难一点,因为您必须考虑到块中的最后一个字节可能是多字节字符的一部分的可能性。

其他 2022/1/1 18:17:57 有463人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶