Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Download all types of files from server using ASP.NET

0.00/5 (No votes)
8 Mar 2012 2  
Download any type of file from server using asp.net with javascript

Introduction

Download any type of file from server using asp.net and javascript. Front end User not able see the files downloading from which server path.

Advantages:

1. Query string not used.

2. User not able to find the path of the file. 

3. User not able to download other files.

Using the code

I used hyperlink control in main.aspx page to download the file, while click the hyperlink page will redirect to download.aspx and it will download the file automatically.

Main.aspx - hyperlink control and javascript

<script type="text/javascript" language="javascript" > 
function InitializeRequest(path) {
	// call server side method 
	PageMethods.SetDownloadPath(path);

	// Create an IFRAME.
	var iframe = document.createElement("iframe"); 
	iframe.src = "Downloads.aspx";

	// This makes the IFRAME invisible to the user.
	iframe.style.display = "none";

	// Add the IFRAME to the page. This will trigger
	// a request to GenerateFile now.
	document.body.appendChild(iframe); 
} 
</script>
Note: If you are using PageMethods in javascript then should be enable the EnablePageMethods is true in asp:ScriptManager control
Ex: <asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:HyperLink NavigateUrl="javascript:void(0)" ID="lnkDownloadHSPressPack" runat="server" >Download File</asp:HyperLink> 
Main.aspx.cs - Call javascript function in hyperlink onclick event

protected void Page_Load(object sender, EventArgs e)
{
	strDownloadPdfLink = "/Documents/PressPack.pdf";
	lnkDownloadHSPressPack.Attributes.Add("onclick", "InitializeRequest('" + strDownloadPdfLink + "');");
}

Web Method for assign the file path to session variable.  This web method call from InitializeRequest javascript function.
/// <summary>
/// WebMethod - Get the PDF path from javascript and assign to session variable
/// </summary>
/// <param name="strpath"></param> 
[System.Web.Services.WebMethod]
public static string SetDownloadPath(string strpath)
{
	Page objp = new Page();
	objp.Session["strDwnPath"] = strpath; 
	return strpath;
}

Downloads.aspx - Download the files based on session, this page redirect from InitializeRequest javascript function (Main.aspx)

after downloaded the file again redirect to main.aspx page

protected void Page_Load(object sender, EventArgs e)
{
string filePath = string.Empty;
try
{
	bool blnFileDownload = false;
	if (!string.IsNullOrEmpty(Session["strDwnPath"].ToString()))
	{
		filePath = Session["strDwnPath"].ToString();
		Session["strDwnPath"] = "";
	}
	if (filePath == "") return;
	Response.Clear();
	// Clear the content of the response
	Response.ClearContent();
	Response.ClearHeaders();
	// Buffer response so that page is sent
	// after processing is complete.
	Response.BufferOutput = true;
	// Add the file name and attachment,
	// which will force the open/cance/save dialog to show, to the header
	string fileName = filePath;
	if (filePath.Contains("/Documents/"))
	{
		fileName = filePath.Split('/')[2];
		blnFileDownload = true;
	}
	else
	{
		blnFileDownload = false;
	}
 
	if (blnFileDownload == true && (File.Exists(Request.PhysicalApplicationPath + filePath) || File.Exists(Server.MapPath(filePath))))
	{
		Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
		Response.ContentType = "application/octet-stream";
		Response.WriteFile(filePath);
		Response.End();
		HttpContext.Current.ApplicationInstance.CompleteRequest();
	}
	else
	{
		if (Request.UrlReferrer != null)
		{
			Type csType = GetType();
			string jsScript = "alert('File Not Found');";
			ScriptManager.RegisterClientScriptBlock(Page, csType, "popup", jsScript, true);
		}
	}
}
catch (Exception ex)
{
	string errorMsg = ex.Message;
}
}
 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here