Last active
May 1, 2024 12:33
-
-
Save moeiscool/b2f0728a5f486b2965ea9b9aa674cf9c to your computer and use it in GitHub Desktop.
jQuery File Download with Progress
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
// 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 | |
} | |
}); |
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
// 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one, just wanted to improve it, by writing it this way:
Will make it even better and this might give you better performances too. 😜