Skip to content

Instantly share code, notes, and snippets.

@sang4lv
Last active December 10, 2015 13:48
Show Gist options
  • Save sang4lv/4442964 to your computer and use it in GitHub Desktop.
Save sang4lv/4442964 to your computer and use it in GitHub Desktop.
Ajax Level 2: Sending large files fast
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { console.log("Upload has finished."); };
xhr.send(blobOrFile);
}
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
var blob = this.files[0];
const BYTES_PER_CHUNK = 1024 * 1024; // 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while(start < SIZE) {
upload(blob.slice(start, end));
start = end;
end = start + BYTES_PER_CHUNK;
}
}, false);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment