How do you show the user a "loading" widget or progress meter while downloading an Excel or other binary file using JQuery without using cookies?
Download Excel or other binary file with loader or progress meter using JQuery without using Cookies
Asked
Active
Viewed 1,008 times
1 Answers
0
$.ajax(url, {
xhrFields: {
responseType: 'arraybuffer'
},
success: function(data, textStatus, jqXHR) {
var blob = new Blob([data], {type: jqXHR.getResponseHeader('content-type')});
var fileName = jqXHR.getResponseHeader('content-disposition').split('filename=')[1].split(';')[0];
saveAs(blob, fileName);
},
progress: function(e) {
if (e.lengthComputable) {
const completedPercentage = Math.round((e.loaded * 100) / e.total);
if (completedPercentage >= 100) {
$("#loader").dialog("close");
}
}
else {
if (console) {
console.log('Content length not reported. Fix this server side.');
}
}
}
});
The Fetch API seems to be a much better way to pull a binary file via ajax, but does not support IE which is a requirement for me. Here is the code I looked at in case it helps anyone. I didn't add the close "loader" logic, but I'm pretty sure you could do that right before or after saving the file.
fetch(url, {
responseType: 'blob'
}).then(response => response.blob())
.then(blob => saveAs(blob, 'test.xlsx'));
This answer was pieced together from the web and several SO posts. See below for relevant links:
- https://stackoverflow.com/a/47197970/1048376 (JQuery and downloading binary data via $.ajax())
- https://stackoverflow.com/a/48437227/1048376 (JQuery and downloading binary data via $.ajax() - I used this solution)
- https://github.com/likerRr/jq-ajax-progress (Lightweight jQuery plugin that adds support of progress and uploadProgress promises to $.ajax() - I used this solution)
- http://www.dave-bond.com/blog/2010/01/JQuery-ajax-progress-HMTL5/ (you could use this instead of the plugin above)
- https://github.com/eligrey/FileSaver.js (FileSaver plugin home - I used this solution)
- https://stackoverflow.com/a/25186103/1048376 (using FileSaver)
- https://github.com/axios/axios (just looked at this, didn't try to implement) https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API (better than JQuery but not IE compatible so not for me)
- https://stackoverflow.com/a/62173022/1048376 (how to get filename from header - I used this solution)
- http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/ (fileDownload plugin home page)
- https://stackoverflow.com/a/9970672/1048376 (excellent post by John Culviner, the fileDownload plugin creator. I have been using this plugin for years, but a Vericode scan is forcing me to use HttpOnly cookies across the board (sigh).)

splashout
- 537
- 5
- 11