-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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