Skip to content

Commit

Permalink
feat(file): adds chunked blob writing (#529)
Browse files Browse the repository at this point in the history
This prevents devices crashing when user picks a big file to write
  • Loading branch information
stalniy authored and ihadeed committed Sep 7, 2016
1 parent 26dead9 commit bbbd0d5
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/plugins/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1119,6 +1119,10 @@ export class File {
* @private
*/
private static write(writer: FileWriter, gu: string | Blob): Promise<void> {
if (gu instanceof Blob) {
return this.writeFileInChunks(writer, gu);
}

return new Promise<void>((resolve, reject) => {
writer.onwriteend = (evt) => {
if (writer.error) {
Expand All @@ -1130,4 +1134,32 @@ export class File {
writer.write(gu);
});
}

/**
* @private
*/
private static writeFileInChunks(writer: FileWriter, file: Blob) {
const BLOCK_SIZE = 1024 * 1024;
let writtenSize = 0;

function writeNextChunk() {
const size = Math.min(BLOCK_SIZE, file.size - writtenSize);
const chunk = file.slice(writtenSize, writtenSize + size);

writtenSize += size;
writer.write(chunk);
}

return new Promise((resolve, reject) => {
writer.onerror = reject;
writer.onwrite = () => {
if (writtenSize < file.size) {
writeNextChunk();
} else {
resolve();
}
};
writeNextChunk();
});
}
}

0 comments on commit bbbd0d5

Please sign in to comment.