Created
March 25, 2014 10:42
-
-
Save keriati/9759016 to your computer and use it in GitHub Desktop.
$.ajax upload progress event callback support
This file contains 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
(function () { | |
// support for uploadProgress callback | |
var originalXHR = $.ajaxSettings.xhr; | |
$.ajaxSetup({ | |
xhr: function () { | |
var myXHR = originalXHR(); | |
if (myXHR.hasOwnProperty('upload') && this.hasOwnProperty('uploadProgress')) { | |
myXHR.upload.addEventListener('progress', this.uploadProgress, false); | |
} | |
return myXHR; | |
} | |
}); | |
// Example request | |
function onUploadProgress(e) { | |
console.log((e.loaded / e.total) * 100 | 0); | |
} | |
function onSuccess() { | |
console.log('request over'); | |
} | |
var file = $('input[type="file"]')[0].files[0], | |
myFormData = new FormData(); | |
myFormData.append(file.name, file); | |
$.ajax({ | |
url: 'http://yoururl', | |
timeout: 120000, | |
method: 'post', | |
processData: false, | |
cache: false, | |
contentType: false, | |
data: myFormData, | |
uploadProgress: onUploadProgress, | |
success: onSuccess | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment