Skip to content

Instantly share code, notes, and snippets.

@adhocore
Last active February 4, 2017 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adhocore/1b0d41530f42a5fbc8f5 to your computer and use it in GitHub Desktop.
Save adhocore/1b0d41530f42a5fbc8f5 to your computer and use it in GitHub Desktop.
AJAX file upload with progress bar, as minimal as it can be.
<?php
/*
* AJAX file upload with progress bar, as minimal as it can be.
* If it doesnot work try latest version of web browser.
*/
// big file upload
ini_set('memory_limit', '1G');
$isXhr = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'
);
$isPost = (isset($_SERVER['REQUEST_METHOD']) &&
$_SERVER['REQUEST_METHOD'] === 'POST'
);
// some checks
if ($isXhr && $isPost && isset($_GET['xhrfile'])) {
$name = $_GET['xhrfile'];
// read
$buffer = file_get_contents('php://input');
// write
if (file_put_contents($name, $buffer)) {
return print 'success';
}
// spit
return print 'error';
}
?>
<style type="text/css">
progress.success { background-color: green; }
progress.error { background-color: red; }
</style>
<form id="upload-form" action="" method="POST" enctype="multipart/form-data">
<input type="file" id="file-input" />
<progress title="" id="progress-bar" value="0" max="100">0 %</progress>
</form>
<script>
// impersonating jQuery :P
function $(id)
{
return document.getElementById(id);
}
// fired after a file selected
function doUpload(evt)
{
var
bar = $('progress-bar'),
xhr = new XMLHttpRequest(),
files = evt.target.files,
// For our example, just upload first file only
file = files[0]
;
// update progress bar class
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
bar.className = xhr.responseText;
}
};
// update progress bar
xhr.upload.addEventListener('progress', function(e) {
var pct = parseInt(e.loaded * 100 / e.total);
bar.value = pct;
bar.title = pct + ' %';
bar.innerHTML = pct + ' %';
}, false);
// ajax post the file data to the form action url
xhr.open('POST', $('upload-form').action + '?xhrfile=' + file.name, true);
xhr.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
xhr.send(file);
}
// register the events!
// (turns out we only have one)
function register()
{
$('file-input').addEventListener('change', doUpload, false);
}
// go
register();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment