通过分块解决慢速读取问题

时间:2014-08-27 14:46:47

标签: javascript

我有一组File,我需要将其内容存储在{name:...,content:...}格式的对象中,其内容为Blob|ArrayBuffer

填写content字段需要阅读File,但使用3MB或更多价值的内容在性能方面非常昂贵(到整个应用程序崩溃的程度)。

目前我正在使用此代码段

var results = []

[File, File, File, ...].forEach(function (file) {
    var reader = new FileReader()

    reader.onload = function() {
        results.push({name: file.name, content: reader.result})
    }

    reader.readAsArrayBuffer(file)
})

出于某些模糊的原因,我想通过

切换到分块解决方案
var results = []

// Chunksize is 1M
var chunkSize = 1024 * 1024 * 1

var fileSize = file.size

// Starting with an empty Blob
var blob = new Blob()

for (var i = 0; i < fileSize; i += chunkSize) {
    (function (f, start) {
        var reader = new FileReader()

        // Slicing file in chunks
        var tmpBlob = f.slice(start, start +chunkSize)

        reader.onload = function() {
            // Merging the old chunks with the just read one
            blob = new Blob([blob, reader.result])

            // If dealing with the last chunk, push
            // the result into the results array
            if (start +chunkSize >= fileSize) {
                results.push({
                    name: file.name,
                    content: blob
                })
            }
        }

        reader.readAsArrayBuffer(tmpBlob)
    })(file, i)
}

0 个答案:

没有答案