How to display download animation when a file is created for download?

I have a web application in which a user can create PDF and PowerPoint files. These files may take some time to generate, so I would like to be able to display the loading animation during its creation. The problem here is that I do not mean to know when the download started. Animation never fades.

I know that it would be possible to create the file “sideways” and notify the user when the file is ready to be downloaded using AJAX, but I prefer to “block” the user while he waits for the download to start.

+8
javascript jquery php
source share
4 answers

To understand what needs to be done here, let's see what usually happens in this query.

  • The user clicks a button to request a file.

  • The file takes time to generate (the user does not receive feedback).

  • The file is completed and begins to be sent to the user.

What we would like to add is feedback for the user to know what we are doing ... Between steps 1 and 2, we need to respond to a click, and we need to find a way to detect when step 3 was done to remove the visual feedback. We will not inform the user about the download status, their browser will do it like with any other download, we just want to tell the user that we are working on their request.

To create a script file for communication with our script requester page, we will use cookies, this ensures that we are not dependent on the browser for events, iframes, etc. After testing several solutions, it seemed the most stable from IE7 to the latest mobile phones.

Step 1.5: Display graphic feedback.

We will use javascript to display notifications on the screen. I chose a simple transparent black overlay on the entire page, so that the user could not interact with other elements of the page, since the following link may deprive him of the ability to receive the file.

$('#downloadLink').click(function() { $('#fader').css('display', 'block'); }); 
 #fader { opacity: 0.5; background: black; position: fixed; top: 0; right: 0; bottom: 0; left: 0; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="fader"></div> <a href="#path-to-file-generator" id="downloadLink">Click me to receive file!</a> </body> 

Step 3.5: Removing the graphic display.

The simple part is done, now we need to notify javascript that the file is loading. When a file is sent to the browser, it is sent with the usual HTTP headers, this allows us to update client cookies. We will use this feature to provide correct visual feedback. Let me change the code above, we will need to set the initial cookie value and listen to its changes.

 var setCookie = function(name, value, expiracy) { var exdate = new Date(); exdate.setTime(exdate.getTime() + expiracy * 1000); var c_value = escape(value) + ((expiracy == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = name + "=" + c_value + '; path=/'; }; var getCookie = function(name) { var i, x, y, ARRcookies = document.cookie.split(";"); for (i = 0; i < ARRcookies.length; i++) { x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); x = x.replace(/^\s+|\s+$/g, ""); if (x == name) { return y ? decodeURI(unescape(y.replace(/\+/g, ' '))) : y; //;//unescape(decodeURI(y)); } } }; $('#downloadLink').click(function() { $('#fader').css('display', 'block'); setCookie('downloadStarted', 0, 100); //Expiration could be anything... As long as we reset the value setTimeout(checkDownloadCookie, 1000); //Initiate the loop to check the cookie. }); var downloadTimeout; var checkDownloadCookie = function() { if (getCookie("downloadStarted") == 1) { setCookie("downloadStarted", "false", 100); //Expiration could be anything... As long as we reset the value $('#fader').css('display', 'none'); } else { downloadTimeout = setTimeout(checkDownloadCookie, 1000); //Re-run this function in 1 second. } }; 
 #fader { opacity: 0.5; background: black; position: fixed; top: 0; right: 0; bottom: 0; left: 0; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="fader"></div> <a href="#path-to-file-generator" id="downloadLink">Click me to receive file!</a> </body> 

Good thing we added here. I put the set / getCookie functions that I use, I don’t know if they are the best, but they work very well. We set the cookie value to 0 when we start the download, this ensures that any other past executions will not interfere. We also initiate a “timeout cycle” to check the cookie value every second. This is the most controversial part of the code, using a timeout to invoke loop functions awaiting a cookie change might not be the best, but it was the easiest way to implement this in all browsers. So, every second we check the cookie value and, if the value is set to 1, we hide the faded visual effect.

Change the server side of the cookie

In PHP, you can do this:

 setCookie("downloadStarted", 1, time() + 20, '/', "", false, false); 

In ASP.Net

 Response.Cookies.Add(new HttpCookie("downloadStarted", "1") { Expires = DateTime.Now.AddSeconds(20) }); 

The cookie name is downloadStarted , its value is 1 , it expires in NOW + 20seconds (we check every second, so more than 20 is enough for this, change this value if you change the timeout value in javascript), its path is on the whole domain (change this to your liking), it is not protected, since it does not contain confidential data and is not HTTP, so our javascript will be able to see it.

Voila! This sums it up. Please note that the code provided works fine with the production application that I work with, but may not suit your specific needs, correct it to your taste.

+26
source share

You can extract the file using the ajax add indicator, then create a tag with dataURI and click on it using JavaScript:

You will need help from this library: https://github.com/henrya/js-jquery/tree/master/BinaryTransport

 var link = document.createElement('a'); if (link.download != undefined) { $('.download').each(function() { var self = $(this); self.click(function() { $('.indicator').show(); var href = self.attr('href'); $.get(href, function(file) { var dataURI = 'data:application/octet-stream;base64,' + btoa(file); var fname = self.data('filename'); $('<a>' + fname +'</a>').attr({ download: fname, href: dataURI })[0].click(); $('.indicator').hide(); }, 'binary'); return false; }); }); } 

You can see the download attribute support on caniuse

and in your html put this:

 <a href="somescript.php" class="download" data-filename="foo.pdf">generate</a> 
+3
source share

This is a simplified version of Salketer's excellent answer. It simply checks for a cookie regardless of its value.

After submitting the form, he will poll the presence of cookies every second. If a cookie exists, the download is still processing. If it is not, the download is complete. There is a 2 minute timeout.

HTML / JS Page:

 var CookieName = "DownloadCompleteChecker"; // unique name for cookie var DownloadTimer; // reference to interval timer var DownloadTimerAttempts = 120; // timeout in seconds function startDownloadChecker(buttonId, imageId) { setCookie(CookieName, 0, DownloadTimerAttempts); // Set an interval timer to check for cookie every second DownloadTimer = window.setInterval(function () { var cookie = getCookie(CookieName); // if cookie doesn't exist, or attempts have expired, re-enable form if ((typeof cookie === 'undefined') || (DownloadTimerAttempts == 0)) { $("#" + buttonId).removeAttr("disabled"); $("#" + imageId).hide(); window.clearInterval(DownloadTimer); expireCookie(CookieName); } DownloadTimerAttempts--; }, 1000); } // form submit event $("#btnSubmit").click(function () { $(this).attr("disabled", "disabled"); // disable form submit button $("#imgLoading").show(); // show loading animation startDownloadChecker("btnSubmit", "imgLoading"); }); <form method="post"> ...fields... <button id="btnSubmit">Submit</button> <img id="imgLoading" src="spinner.gif" style="display:none" /> </form> 

Javascript support for setting / receiving / deleting cookies:

 function setCookie(name, value, expiresInSeconds) { var exdate = new Date(); exdate.setTime(exdate.getTime() + expiresInSeconds * 1000); var c_value = escape(value) + ((expiresInSeconds == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = name + "=" + c_value + '; path=/'; }; function getCookie(name) { var parts = document.cookie.split(name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } function expireCookie(name) { document.cookie = encodeURIComponent(name) + "=; path=/; expires=" + new Date(0).toUTCString(); } 

Server-side code in ASP.Net:

 ...generate big document... // attach expired cookie to response to signal download is complete var cookie = new HttpCookie("DownloadCompleteChecker"); // same cookie name as above! cookie.Expires = DateTime.Now.AddDays(-1d); // expires yesterday HttpContext.Current.Response.Cookies.Add(cookie); // Add cookie to response headers HttpContext.Current.Response.Flush(); // send response 

Hope this helps! :)

+1
source share

Spin.js is great for this and is easy to modify. You can download the .js file from GitHub or google. Then, to make it work, just add a button click event or even better for those using ASP.NET web forms, add a trigger to send events to the form tag ...

This is the trigger that I usually use: <form id="form1" runat="server" onsubmit="loader();">

And the bootloader function with spin settings:

 <script type="text/javascript"> function loader() { document.getElementById('loader').style.display = 'block'; } </script> <script src="Scripts/Spin.min.js" type="text/javascript"></script> <script type="text/javascript"> var opts = { lines: 15, // The number of lines to draw length: 25, // The length of each line width: 3, // The line thickness radius: 20, // The radius of the inner circle corners: 0.6, // Corner roundness (0..1) rotate: 0, // The rotation offset direction: 1, // 1: clockwise, -1: counterclockwise color: '#005293', // #rgb or #rrggbb or array of colors speed: 3, // Rounds per second trail: 70, // Afterglow percentage shadow: true, // Whether to render a shadow hwaccel: false, // Whether to use hardware acceleration className: 'spinner', // The CSS class to assign to the spinner zIndex: 2e9, // The z-index (defaults to 2000000000) top: '50%', // Top position relative to parent left: '50%' // Left position relative to parent }; var target = document.getElementById('loader'); var spinner = new Spinner(opts).spin(target); </script> 

You also need a div to hold the bootloader:

 <div class="loader" id="loader" style="display:none;"></div> 

There are also some css settings:

 .loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999; background: rgb(50, 50, 50) no-repeat 50% 50%; opacity: 0.8; filter: alpha(opacity=80); } 
-4
source share

All Articles