I try to download a CSV file and then do something after download has finished. So I need to implement an appropriate callback
function.
Using window.location="..."
is not a good idea because I cannot operate the program after finishing download. Something like this, change header so it is not a good idea.
fetch
is a good alternative however it cannot support IE 11. And window.URL.createObjectURL
cannot support IE 11.You can refer this.
This is my code, it is similar to the code of Shahrukh Alam. But you should take care that window.URL.createObjectURL
maybe create memory leaks. You can refer this. When response has arrived, data will be stored into memory of browser. So before you click a
link, the file has been downloaded. It means that you can do anything after download.
$.ajax({
url: 'your download url',
type: 'GET',
}).done(function (data, textStatus, request) {
// csv => Blob
var blob = new Blob([data]);
// the file name from server.
var fileName = request.getResponseHeader('fileName');
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { // for others
var url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
//Do something after download
...
}
}).then(after_download)
}