javascript - 在 cordova-plugin-file (iOS) 的 FileReader 上调用 readAsArrayBuffer 方法时出现内存不足错误
问题描述
在 iOS 上,我正在尝试将视频上传到我自己的网站,为此我使用了具有 1048576 的 chunkSize 的 FileReader.readAsArrayBuffer 方法。
我在 onprogress 事件触发时上传块,所有这些实际上都非常完美,除了更大的文件。尝试上传 1.33GB 的文件时,调用 readAsArrayBuffer 方法时出现内存不足异常。
我猜这是因为它试图为整个文件保留内存,但这不是必需的。有没有办法从文件中读取二进制块而不为完整文件保留内存?还是有其他解决方案?
谢谢!
解决方案
我今天通过更改插件代码自己修复了它,这是原始代码:
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(除了拉代码),所以我暂时不上传这个,我可能会在不久的将来研究它。
推荐阅读
- pandas - 根据熊猫中最后一个单元格字符串对数据框列进行排序
- javascript - ASP.NET Core 3.1 CORS 配置出错
- docker - 将网络连接到服务
- asp.net-core - dotnet 核心日志记录始终显示信息结果
- image - 在 Groovy 中将 Base64 字符串转换为图像文件
- woocommerce - 在 woocommerce 4.5.2 中关闭 paypal 作为付款选项
- c - python send() 中的消息长度类似于 C 中的 send()
- ios - 运行 hotrestart 时出错:“发生意外错误,进程已终止”
- php - 用 php 和 curl 显示 instagram 提要是一种好方法吗?
- javascript - 将输入给定值更改为 ReactJS 中的自定义值