Click here to Skip to main content
Click here to Skip to main content

Download all types of files from server using ASP.NET

, 8 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ramanujam Shankar
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
No Biography provided

Comments and Discussions

 
QuestionHi PinmemberRahim Lotfi19-Feb-14 11:02 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411022.1 | Last Updated 8 Mar 2012
Article Copyright 2012 by Ramanujam Shankar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid