Skip to content

Instantly share code, notes, and snippets.

@lumie1337
Last active July 26, 2020 13:17
Show Gist options
  • Save lumie1337/57447bda4d613dbec2a937dbad724de4 to your computer and use it in GitHub Desktop.
Save lumie1337/57447bda4d613dbec2a937dbad724de4 to your computer and use it in GitHub Desktop.
const defaultChunkSize = 1 * 1024 * 1024; // 1 MB
const chunkBlob = ({chunkSize = defaultChunkSize, blob}) => {
function* go(offset, chunkId) {
if(offset < blob.size) {
const nextOffset = offset + chunkSize + 1;
yield {
chunkId,
chunk: file.slice(offset, nextOffset)
};
yield* go(nextOffset, chunkId + 1);
}
}
return go(0, 0);
}
const uploadChunk = ({chunk, chunkId}) =>
$.ajax({
// do the request here
})
async function example(file) {
Promise.all(chunkBlob(file).map(async function({chunk, chunkId}) {
const chunkArrayBuffer = await readBlobAsync(chunk);
return uploadChunk({chunk: chunkArrayBuffer, chunkId});
}));
}
const readBlobAsync = (blob) =>
new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result)
reader.onerror = reject;
reader.readAsArrayBuffer(blob);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment