Slice a file

suggest change

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 into a given number of blobs. slice does not include the byte at byteEnd. This is useful when a file is too large to read into memory all at once. The chunks can then be read one by one with FileReader. If chunksAmount is greater than file.size, some slices are empty.

function sliceFile(file, chunksAmount) {
  let byteIndex = 0;
  const chunks = [];
    
  for (let i = 0; i < chunksAmount; i += 1) {
    const byteEnd = Math.ceil((file.size / chunksAmount) * (i + 1));
    chunks.push(file.slice(byteIndex, byteEnd));
    byteIndex += (byteEnd - byteIndex);
  }

  return chunks;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents