Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@moeiscool
Last active September 7, 2019 00:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moeiscool/b2f0728a5f486b2965ea9b9aa674cf9c to your computer and use it in GitHub Desktop.
Save moeiscool/b2f0728a5f486b2965ea9b9aa674cf9c to your computer and use it in GitHub Desktop.
jQuery File Download with Progress
// Found at https://stackoverflow.com/questions/19126994/what-is-the-cleanest-way-to-get-the-progress-of-jquery-ajax-request
var url = "REMOTE_URL"
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
}
}, false);
return xhr;
},
type: 'GET',
url: url,
data: {},
success: function(data){
//Do something on success
}
});
// Found at https://usefulangle.com/post/68/javascript-ajax-download-file
var url = "REMOTE_URL"
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total * 100).toFixed(2);
onProgress(percentComplete)
}
}, false)
xhr.addEventListener('readystatechange', function(e) {
if(xhr.readyState == 2 && xhr.status == 200) {
// Download is being started
}
else if(xhr.readyState == 3) {
// Download is under progress
}
else if(xhr.readyState == 4) {
onSuccess(xhr.response)
// Downloaing has finished
// request.response holds the file data
}
})
xhr.responseType = 'blob'
xhr.open('get', url)
xhr.send()
@Jiab77
Copy link

Jiab77 commented Aug 25, 2019

Nice one, just wanted to improve it, by writing it this way:

$.ajax({
    // Your ajax call
})
.done(function () {
    // Success code
})
.fail(function () {
    // Fail code
});

Will make it even better and this might give you better performances too. 😜

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment