Skip to content

Instantly share code, notes, and snippets.

@rozmiarek
Forked from HenrikJoreteg/ajaxfileupload.js
Created April 26, 2012 20:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rozmiarek/2502983 to your computer and use it in GitHub Desktop.
Save rozmiarek/2502983 to your computer and use it in GitHub Desktop.
AJAX file uploading using jQuery and XMLHttpRequest 2.0 and adding listener for progress updates
// grab your file object from a file input
$('#fileInput').change(function () {
sendFile(this.files[0]);
});
// can also be from a drag-from-desktop drop
$('dropZone')[0].ondrop = function (e) {
e.preventDefault();
sendFile(e.dataTransfer.files[0]);
};
function sendFile(file) {
$.ajax({
type: 'post',
url: '/targeturl?name=' + file.fileName,
data: file,
success: function () {
// do something
},
xhrFields: {
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
onprogress: function (progress) {
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);
// log upload progress to console
console.log('progress', percentage);
if (percentage === 100) {
console.log('DONE!');
}
}
},
processData: false,
contentType: file.type
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment