Skip to content

Instantly share code, notes, and snippets.

@gtechsltn
Forked from HenrikJoreteg/ajaxfileupload.js
Created March 14, 2024 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtechsltn/3cd830c6698e788c3c0e2a31ab4e6bf2 to your computer and use it in GitHub Desktop.
Save gtechsltn/3cd830c6698e788c3c0e2a31ab4e6bf2 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