Click here to Skip to main content
15,885,309 members
Articles / Web Development / ASP.NET
Tip/Trick

Download all types of files from server using ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.70/5 (3 votes)
8 Mar 2012CPOL 50.1K   7   1
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

C++
<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>
C++
Note: If you are using PageMethods in javascript then should be enable the EnablePageMethods is true in asp:ScriptManager control
C++
Ex: <asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
C++
<asp:HyperLink NavigateUrl="javascript:void(0)" ID="lnkDownloadHSPressPack" runat="server" >Download File</asp:HyperLink> 
C++
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.
C++
/// <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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHi Pin
Rahim Lotfi19-Feb-14 10:02
Rahim Lotfi19-Feb-14 10:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.