Created
May 13, 2020 17:33
-
-
Save tejpaldev/c2d8181d4df4a2b8d3fe7a997ca7b52d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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