Forcing Download on Web page

Here I’m explaining how to create a webpage that offers download on button click event, instead of showing a direct link to the download file. The following C# piece of code when inserted in button click event on ASP.net web page, gives you an effect of dynamic download, hiding download URL.

HTTP requests and responses travel along with lot of headers, just like meta-data for the request/response. Here is the list of some of them, Response Headers. Following example makes use of them. The method implemented here is just for the sake of example, and not to be used on Web Servers. Problem here is we are reading one byte, writing to response and flushing the response again-n-again. Here for every single byte, a packet is created and sent to the client, creating packet flood! Using a buffer of at least 1000 bytes before flushing is recommended.

Response.Clear();
String fileNameToSend = “downloadTest.txt”;

//Make sure following file exists and it’s size is less than 2KB.
FileInfo file = new FileInfo( “C:test.txt” );
String value = “attachment; filename=”" + fileNameToSend + “”";
Response.ContentType = “application/octet-stream” ;
Response.AddHeader(“Content-length: “, file.Length.ToString());
Response.AddHeader(“Content-Disposition”, value );
FileStream fs = null ;
try {
   fs = File.OpenRead(“C:test.txt”);
   BinaryReader br = new BinaryReader(fs);
   while (true)
   {
       // EOF exception to exit loop, not a good way!
       Response.Write((char)br.ReadByte());
       System.Threading.Thread.Sleep(5);
       Response.Flush();
   }
}
catch {}
finally
{
   if (fs != null )
      fs.Close();
}
Response.End();

What more you can do with this?

  • allow users to download only one file at a time,
  • limit bandwidth for specific users, etc.

~ ankit

Comments (1) left to “Forcing Download on Web page”

  1. ये मेरी लाईफ है - चिराग मेहता » Blog Archive » Download on button click event wrote:

    […] http://ankitjain.info/ankit/2006/07/01/forcing-download-on-web-page […]

Post a Comment

*Required
*Required (Never published)
 

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image

Investing in solid website hosting, one that can support your web design, choices, is definitely worth the time and money. For some companies having things like self inking stamps as well as personalized checks are just as important for day to day business.