Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save priyankakundu/81313e4a628361b7af49bf0fc85d1903 to your computer and use it in GitHub Desktop.
Save priyankakundu/81313e4a628361b7af49bf0fc85d1903 to your computer and use it in GitHub Desktop.
1.Create a cookie before writing the stream to Response.
2.Use JavaScript timer to check whether the value of cookie is set to true
3.If downloaded cookie is true, display a message that file download is successful and erase cookie
<script>
var timer;
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function eraseCookie(name) {
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
function checkDownloadStatus() {
var isDownloaded = getCookie("downloaded");
//check if downloaded cookie value is true
if (isDownloaded == 'true') {
downloadedmessage.innerHTML = "File successfully downloaded";
clearInterval(timer);
//remove cookie
eraseCookie("downloaded");
}
}
function downloadButtonClick() {
downloadedmessage.innerHTML = 'Please wait while your file is being downloaded';
//check status every 300ms
timer = setInterval(checkDownloadStatus, 300);
return true;
}
</script>
<form id="form1" runat="server">
<asp:Button Text="Download File" ID="btnDownload" runat="server" OnClick="btnDownload_Click" OnClientClick="return downloadButtonClick();" />
<div id="downloadedmessage" style="font-family: Tahoma; font-size: small;">
</div>
</form>
protected void btnDownload_Click(object sender, EventArgs e)
{
Byte[] bytes = File.ReadAllBytes(@"c:\\printdocument.pdf");
Response.AddHeader("Content-Disposition", "attachment; filename=" + "print.pdf");
Response.ContentType = "application/pdf";
//set cookie for tracking download status
HttpCookie myCookie = new HttpCookie("downloaded");
myCookie.Value = "true";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
//simulate download wait
System.Threading.Thread.Sleep(5000);
Response.BinaryWrite(bytes.ToArray());
Response.End();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment