Automatically download a document when the page loads

I had a requirement to start a download of a file automatically once my custom application page loads. After trying a couple of approaches, I found this approach which works consistently across browsers. It also turns out to only be a few lines of code. I’ve refactored it into the method below.

// <summary>

/// Adds an HtmlMeta tag to page that tells the browser to download the given file automatically when the page loads

/// </summary>

/// <param name="secondsToWait">Determines how many seconds will pass before the automatic download will begin</param>

/// <param name="fileURL">The URL of the file you want to download</param>

private void CreateFileDownloadMetaTag(int secondsToWait, string fileURL)

{

HtmlMeta meta = new HtmlMeta();

meta.HttpEquiv = "Refresh";

meta.Content = String.Format("{0};URL='{1}'", secondsToWait, fileURL);

this.Page.Header.Controls.Add(meta);

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.