Created
February 20, 2021 19:27
-
-
Save gustavonovaes/04b85bcfbff401cccbb03d5a839dc865 to your computer and use it in GitHub Desktop.
Sending large binary data with XMLHTTPRequest to PHP as stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ($_SERVER['REQUEST_METHOD'] === 'POST') { | |
$filePath = __DIR__ . '/out.tmp'; | |
$input = fopen('php://input', 'r'); | |
$output = fopen($filePath, 'w+'); | |
stream_copy_to_stream($input, $output); | |
fclose($input); | |
fclose($output); | |
exit(0); | |
} | |
?> | |
<form id="upload" action="" method="post"> | |
<label for="file">file:</label> | |
<input name="file" type="file"> | |
<button type="submit">Upload</button> | |
</form> | |
<script> | |
const form = document.forms.upload; | |
const inputFile = form.elements.file; | |
async function fileToBlob(file) { | |
return new Blob([new Uint8Array(await file.arrayBuffer())], { type: file.type }); | |
} | |
function sendToServer(url, data) { | |
const req = new XMLHttpRequest(); | |
req.open("POST", url, true); | |
req.send(data); | |
} | |
async function onSubmit(e) { | |
e.preventDefault(); | |
const file = inputFile.files[0]; | |
sendToServer('/', await fileToBlob(file)); | |
} | |
form.addEventListener('submit', onSubmit); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment