Skip to content

Instantly share code, notes, and snippets.

@egobrain
Created April 6, 2012 05:44
Show Gist options
  • Save egobrain/2317351 to your computer and use it in GitHub Desktop.
Save egobrain/2317351 to your computer and use it in GitHub Desktop.
File upload example that uses new Browser HTML5 Upload API.
<style>
#dropZone {
color: #555;
font-size: 18px;
text-align: center;
width: 400px;
padding: 50px 0;
margin: 50px auto;
background: #eee;
border: 1px solid #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#dropZone.hover {
background: #ddd;
border-color: #aaa;
}
#dropZone.drop {
background: #afa;
border-color: #0f0;
}
#dropZone.error {
background: #faa;
border-color: #f00;
}
</style>
<form action="upload" method="">
<div id="dropZone">
Drug here please
</div>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(function(){
var dropZone = $('#dropZone');
maxFileSize = 1000000;
if(typeof(window.FileReader) == 'undefined') {
dropZone.text('Unsupported');
dropZone.addClass('error');
}
dropZone[0].ondragover = function() {
dropZone.addClass('hover');
return false;
};
dropZone[0].ondragleave = function() {
dropZone.removeClass('hover');
return false;
};
dropZone[0].ondrop = function(event) {
event.preventDefault();
dropZone.removeClass('hover');
dropZone.addClass('drop');
var file = event.dataTransfer.files[0];
if (file.size > maxFileSize) {
dropZone.text('File is too big!');
dropZone.addClass('error');
return false;
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.onreadystatechange = stateChange;
xhr.open('POST', '/upload',true);
xhr.setRequestHeader("X-FILE-NAME", file.name);
xhr.send(file);
};
function uploadProgress(event) {
var percent = parseInt(event.loaded / event.total * 100);
dropZone.text('Uploading: ' + percent + '%');
}
function stateChange(event) {
if (event.target.readyState == 4) {
if (event.target.status == 200) {
dropZone.text('Success!');
} else {
dropZone.text('Error!');
dropZone.addClass('error');
}
}
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment