TypedArray.prototype.slice() not supported on Chrome

浪尽此生 提交于 2019-12-12 03:24:57

问题


I would like to upload large files, using Uint8Array and slice() function. The slice() is needed, because large files have to be handled too.

var fileReader = new FileReader();

fileReader.onloadend = function(event) {
    var contents = new Uint8Array(event.target.result);

    var bufferSize = 8192;
    var byteBuffer = [];

    var temp = null;
    var pos = 0;
    for(var i = 0; i < contents.length; i+=bufferSize) {
        pos =  contents.length > i+bufferSize ? i+bufferSize : contents.length;
        byteBuffer.push(String.fromCharCode.apply(null, contents.slice(i, pos)));
    }

    var bytes = byteBuffer.join('');

    contents = undefined;
    byteBuffer = undefined;

    var formData = new FormData();
    formData.append('name', 'somefile.dat');
    formData.append('data', bytes);

    // do the POST formData

};

The code above works only in Firefox.

The Uint8Array is supported on all browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array

The problem is the Uint8Array is inherited from TypedArray, and the code above uses the TypedArray.prototype.slice() function. Which is only supported in Firefox: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice

There is a subarray() function too, but that doesn't create a shallow copy. While processing large files, it's not a good idea to create deep copy.

I looked at the lodash's slice() too, but it's for Array and not TypedArray. So that is not working for me.

Maybe I should write a function to create a shallow copy of the subarray?


回答1:


Just use subarray() in place of slice().

The two works the same here, and it might be calling the same internal implementation. See the benchmarks using Firefox: http://jsperf.com/array-slice-vs-typedarray-subarray

( However, the documentation for TypedArray.slice() and TypedArray.subarray() is slightly different: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array )



来源:https://stackoverflow.com/questions/35313993/typedarray-prototype-slice-not-supported-on-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!