Skip to content

Instantly share code, notes, and snippets.

@ryanguill
Created August 11, 2014 17:03
Show Gist options
  • Save ryanguill/6dddbbc9b226380e1d6f to your computer and use it in GitHub Desktop.
Save ryanguill/6dddbbc9b226380e1d6f to your computer and use it in GitHub Desktop.
<html>
<head>
<title>JS File Upload</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="inpFile" value="" />
<input type="button" id="btnUpload" value="upload" />
<script>
function navigateAwayWarning () {
return 'Please allow upload to finish before navigating away from page.'
}
$("#btnUpload").on("click", function(e) {
var files = document.getElementById("inpFile").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fd = new FormData();
fd.append('file', file);
fd.append('filesize', file.size);
fd.append('filetype', file.type);
fd.append('filename', file.name);
sendFileToServer(fd);
}
});
function sendFileToServer(formData, status){
var uploadURL = 'http://example.com/fileUpload'
, extraData ={} //Extra Data.
, jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
window.onbeforeunload = navigateAwayWarning; /*set the navigate away warning */
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//you could do something with the percent here like update a progress bar
if (percent === 100) {
window.onbeforeunload = null; /*remove warning when upload is complete*/
}
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment