首页 > 解决方案 > 在 cordova-plugin-file (iOS) 的 FileReader 上调用 readAsArrayBuffer 方法时出现内存不足错误

问题描述

在 iOS 上,我正在尝试将视频上传到我自己的网站,为此我使用了具有 1048576 的 chunkSize 的 FileReader.readAsArrayBuffer 方法。

我在 onprogress 事件触发时上传块,所有这些实际上都非常完美,除了更大的文件。尝试上传 1.33GB 的文件时,调用 readAsArrayBuffer 方法时出现内存不足异常。

我猜这是因为它试图为整个文件保留内存,但这不是必需的。有没有办法从文件中读取二进制块而不为完整文件保留内存?还是有其他解决方案?

谢谢!

标签: javascriptcordovacordova-plugin-file

解决方案


我今天通过更改插件代码自己修复了它,这是原始代码:

FileReader.prototype.readAsArrayBuffer = function (file) {
   if (initRead(this, file)) {
       return this._realReader.readAsArrayBuffer(file);
   }

   var totalSize = file.end - file.start;
   readSuccessCallback.bind(this)('readAsArrayBuffer', null, file.start, totalSize, function (r) {
       var resultArray = (this._progress === 0 ? new Uint8Array(totalSize) : new Uint8Array(this._result));
       resultArray.set(new Uint8Array(r), this._progress);
       this._result = resultArray.buffer;
   }.bind(this));
};

并且由于在开始时进度始终为 0,因此它始终保留整个文件大小。我添加了一个属性 READ_CHUNKED (因为我仍然有其他现有代码也使用此方法并希望它像以前那样工作,我必须检查以查看其他所有内容是否也继续工作)并将上面的内容更改为:

FileReader.prototype.readAsArrayBuffer = function(file) {
    if (initRead(this, file)) {
        return this._realReader.readAsArrayBuffer(file);
    }

    var totalSize = file.end - file.start;

    readSuccessCallback.bind(this)('readAsArrayBuffer', null, file.start, totalSize, function(r) {
        var resultArray;

        if (!this.READ_CHUNKED) {
            resultArray = new Uint8Array(totalSize);
            resultArray.set(new Uint8Array(r), this._progress);
        } else {
            var newSize = FileReader.READ_CHUNK_SIZE;
            if ((totalSize - this._progress) < FileReader.READ_CHUNK_SIZE) {
                newSize = (totalSize - this._progress);
            }
            resultArray = new Uint8Array(newSize);
            resultArray.set(new Uint8Array(r), 0);
        }
        this._result = resultArray.buffer;
    }.bind(this));
};

当 READ_CHUNKED 属性为真时,它只返回块并且不为整个文件保留内存,当它为假时,它像以前一样工作。

我从来没有使用过 github(除了拉代码),所以我暂时不上传这个,我可能会在不久的将来研究它。


推荐阅读