Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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