Skip to content

Instantly share code, notes, and snippets.

@radxene
Last active August 25, 2017 21:37
Show Gist options
  • Save radxene/7f864aeecfef8ce29519b7cb2264d477 to your computer and use it in GitHub Desktop.
Save radxene/7f864aeecfef8ce29519b7cb2264d477 to your computer and use it in GitHub Desktop.
Send big file to server
<?php
$filename = !empty($_GET["filename"]) ? $_GET["filename"] : null;
if ($filename) {
$chunk = file_get_contents("php://input");
file_put_contents($filename, $chunk, FILE_APPEND);
}
?>
Load file: <input type="file" id="bigfile" />
<script>
document.getElementById("bigfile").addEventListener("change", uploadFile);
function uploadFile(event){
const file = event.target.files[0];
const total = file.size;
const start = 0;
const step = 1024 * 1024;
let blob = file.slice(start, step);
let loaded = 0;
const reader = new FileReader();
reader.addEventListener("load", function(event) {
const xhr = new XMLHttpRequest();
const upload = xhr.upload;
upload.addEventListener("load", function() {
loaded += step;
if(loaded <= total) {
blob = file.slice(loaded, loaded+step);
reader.readAsBinaryString(blob);
} else {
loaded = total;
}
}, false);
xhr.open("POST", `send-bigfile.php?filename=${file.name}&nocache=${new Date().getTime()}`);
xhr.overrideMimeType("application/octet-stream");
xhr.sendAsBinary(event.target.result);
});
reader.readAsBinaryString(blob);
}
if (!XMLHttpRequest.prototype.sendAsBinary) {
XMLHttpRequest.prototype.sendAsBinary = function (sData) {
const nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
for (let nIdx = 0; nIdx < nBytes; nIdx++) {
ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
}
this.send(ui8Data);
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment