File size: 932 Bytes
181e22f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const CHUNK_SIZE = 64 * 1024;

class FileChunker {
  constructor(file) {
    this.file = file;
    this.reader = new FileReader();
    this.offset = 0;
  }

  getNextChunk() {
    return new Promise((resolve, reject) => {
      if (this.offset >= this.file.size) {
        resolve({
          done: true,
        });
      }

      this.reader.onload = (e) => {
        const chunk = e.target.result;
        this.offset += chunk.byteLength;
        resolve({
          done: this.offset >= this.file.size,
          chunk,
          offset: this.offset,
        });
      };
      this.reader.onabort = () => {
        reject(new Error('FileReader abort'));
      };
      this.reader.onerror = (evt) => {
        reject(new Error('FileReader onerror' + evt));
      };
      const blob = this.file.slice(this.offset, this.offset + CHUNK_SIZE);
      this.reader.readAsArrayBuffer(blob);
    });
  }
}

export default FileChunker;