Detect download is ready on page that started download
Generating some files in views for downloading may take a considerable time for some tasks. So it will be a good idea to let the user know that all is ok and he should wait. Assume You have some block that shows the user that you are preparing for file download
<div id="preparing-div" hidden>
<div>
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<br><br>Preparing file for download...
</div>
</div>
Example css:
#preparing-div {
position: fixed;
top: 0;
left: 0;
color: white;
background-color: #000;
opacity: 0.7;
width: 100%;
height: 100%;
font-size: 3em;
text-align: center;
}
#preparing-div div {
position: relative;
top: 50%
}
Add download_file
which will generate some random value and send it via GET
param. Then we will monitor some cookie, and when the server will return response it will set this cookie to our value:
function getCookie( name ) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function download_file() {
document.getElementById('preparing-div').removeAttribute('hidden');
var doneIndicator = parseInt((Math.random() * 100000), 10);
window.location.href = '/dwonload-something/?doneIndicator=' + doneIndicator;
var pool_ms = 200;
var attempts = 40 * (1000/pool_ms); // 40 second max
var downloadTimer = window.setInterval( function() {
var cookieDoneIndicator = getCookie("cookieDoneIndicator");
if( (cookieDoneIndicator == doneIndicator) || (attempts == 0) ) {
document.getElementById('preparing-div').setAttribute('hidden', 'true');
clearInterval(downloadTimer);
}
attempts--;
}, pool_ms);
On backend set cookie from GET
parameter. Python Django example:
response = HttpResponse(content_type='FILE_CONTENT_TYPE')
response.set_cookie('cookieDoneIndicator', request.GET.get('doneIndicator'))