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

One thought on “Forcing Download on Web page

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

Leave a Reply

Your email address will not be published. Required fields are marked *