Skip to content Skip to sidebar Skip to footer

File.slice Fails Second Time

I'm trying to make a (front-end) Javascript that would be able to copy very large files (i.e. read them from a file input element and 'download' them using StreamSaver.js). This i

Solution 1:

I would go with something like blob.stream() or new Response(blob).body to read all chunks of the file and potentially a TransformStream if needed. But if you need a custom slice size or better browser support than you can create your own blob -> readableStream utility

// Taken from https://www.npmjs.com/package/screw-filereaderfunctionstream (blob) {
  var position = 0var blob = thisreturnnewReadableStream({
    pull (controller) {
      var chunk = blob.slice(position, position + 1048576)

      return chunk.arrayBuffer().then(buffer => {
        position += buffer.byteLengthvar uint8array = newUint8Array(buffer)
        controller.enqueue(uint8array)

        if (position == blob.size)
          controller.close()
      })
    }
  })
}

stream(blob).pipeTo(writeStream)

This way you can just pipe it to streamsaver instead of writing each chunk manually

Post a Comment for "File.slice Fails Second Time"