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?