AUTHOR: Peter Milchev
DATE POSTED: October 15, 2018
Detect when the file is ready to start downloading.
Usually, when a file is being downloaded, the server clears the response and responds with the file to download.
To workaround this, we can add a cookie to the response on the server and look for it in the client-side. To achieve that, before sending the request to the server, we can start checking for this cookie on a given interval of time until the cookie is present. Once the cookie is present, we will know that the server responded with the file and we can do our custom logic and clear the cookie.
<
telerik:RadButton
runat
=
"server"
ID
"RadButton1"
OnClientClicking
"OnClientClicking"
OnClick
"RadButton1_Click"
Text
"Download File"
AutoPostBack
"true"
/>
function
OnClientClicking(sender, args) {
pollingAPI.startPolling(
(cookieMessage) {
alert(cookieMessage)
}, 200);
}
var
cookieAPI = (
(undefined) {
clearCookie(cookieName) {
setCookie(cookieName,
""
,
new
Date());
// https://www.w3schools.com/js/js_cookies.asp
getCookie(cname) {
name = cname +
"="
;
decodedCookie = decodeURIComponent(document.cookie);
ca = decodedCookie.split(
';'
);
for
(
i = 0; i < ca.length; i++) {
c = ca[i];
while
(c.charAt(0) ==
' '
) {
c = c.substring(1);
if
(c.indexOf(name) == 0) {
return
c.substring(name.length, c.length);
setCookie(cname, cvalue, exdays) {
d =
Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
expires =
"expires="
+ d.toUTCString();
document.cookie = cname +
+ cvalue +
";"
+ expires +
";path=/"
{
getCookie: getCookie,
setCookie: setCookie,
clearCookie: clearCookie
})();
pollingAPI = (
(cookieAPI) {
startPolling(callbackFunction, pollingInterval) {
cookieName =
"file-download"
pollingInterval = pollingInterval || 500;
cookieAPI.clearCookie(cookieName);
interval = setInterval(
() {
cookieMessage = cookieAPI.getCookie(cookieName);
clearInterval(interval);
// use message form server
callbackFunction(cookieMessage)
//console.log(cookieMessage);
// clear cookie
cookieAPI.clearCookie(cookieName)
}, pollingInterval);
startPolling: startPolling
})(cookieAPI);
protected
void
RadButton1_Click(
object
sender, EventArgs e)
Response.Clear();
//Indicate the type of data being sent
Response.ContentType =
"application/octet-stream"
//Name the file
Response.AddHeader(
"Content-Disposition"
"attachment; filename=\"someFile.txt\""
// simulate long server processing
Thread.Sleep(4000);
Response.BinaryWrite(Encoding.UTF8.GetBytes(
"This is a dummy file"
));
// add cookie to know the file begins downloading
HttpCookie myCookie =
HttpCookie(
myCookie.Value =
"The file started downloading!"
HttpContext.Current.Response.Cookies.Add(myCookie);
Response.End();
Resources Buy Try