The blob.slice()
method is used to create a new Blob object containing the data in the specified range of bytes of the source Blob. This method is usable with File instances too, since File extends Blob.
Here we slice a file in a specific amount of blobs. This is useful especially in cases where you need to process files that are too large to read in memory all in once. We can then read the chunks one by one using FileReader
.
/**
* @param {File|Blob} - file to slice
* @param {Number} - chunksAmount
* @return {Array} - an array of Blobs
**/
function sliceFile(file, chunksAmount) {
var byteIndex = 0;
var chunks = [];
for (var i = 0; i < chunksAmount; i += 1) {
var byteEnd = Math.ceil((file.size / chunksAmount) * (i + 1));
chunks.push(file.slice(byteIndex, byteEnd));
byteIndex += (byteEnd - byteIndex);
}
return chunks;
}