Wednesday, September 10, 2008

Large File Download using HTTPHandler

The below mentioned code-segment prompts you with an Open-Save-Cancel window. If you need a Save-Dialogue box instead of Open-Save-Cancel window, just include the below code:

Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

instead of

Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

Complete Code:

// Page-Load
protected void Page_Load(object sender, EventArgs e)

// File Download Function
private void DownloadFile()
   string filepath = Server.MapPath("samplefile.doc");

   FileInfo file = new FileInfo(filepath);
   if (file.Exists)
      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
      Response.AddHeader("Content-Length", file.Length.ToString());
      string fExtn = GetFileExtension(file.Extension.ToLower());
      Response.ContentType = fExtn;

// Gets File Extension
private string GetFileExtension(string fileExtension)
   switch (fileExtension)
      case ".htm":
      case ".html":
      case ".log":
         return "text/HTML";

      case ".txt":
         return "text/plain";

      case ".doc":
         return "application/ms-word";

      case ".tiff":
      case ".tif":
         return "image/tiff";

      case ".asf":
         return "video/x-ms-asf";

      case ".avi":
         return "video/avi";

      case ".zip":
         return "application/zip";

      case ".xls":
      case ".csv":
         return "application/";

      case ".gif":
         return "image/gif";

      case ".jpg":
      case "jpeg":
         return "image/jpeg";

      case ".bmp":
         return "image/bmp";

      case ".wav":
         return "audio/wav";

      case ".mp3":
         return "audio/mpeg3";

      case ".mpg":
      case "mpeg":
         return "video/mpeg";

      case ".rtf":
         return "application/rtf";

      case ".asp":
         return "text/asp";

      case ".pdf":
         return "application/pdf";

      case ".fdf":
         return "application/vnd.fdf";

      case ".ppt":
         return "application/mspowerpoint";

      case ".dwg":
         return "image/vnd.dwg";

      case ".msg":
         return "application/msoutlook";

      case ".xml":
      case ".sdxl":
         return "application/xml";

      case ".xdp":
         return "application/vnd.adobe.xdp+xml";

         return "application/octet-stream";

Response.TransmitFile() vs Response.WriteFile()

TransmitFile() method sends the file to the client without loading it to the application memory on the server. So, It is ideal to use for large files.

WriteFile() method loads the file being download to the server's memory before sending it to the client. It is ideal for small and medium size files.

No comments:

Best viewed in Internet Explorer 8.