29 June 2005

Forcing File Downloads (PHP/C#/ASP)

Posted by Mikhail Esteves under: C#; LAMP; Tips .

For known MIME types, browsers default to automatically displaying content of the format within the browser window, natively. However, in many scenarios where you present an image, PDF file, etc for the user to download, you may not want this to happen and may want the user to see the file download box instead. Here is how you can do this:

A simple PHP example:

$theFile = "images/dlimg.png";

ob_start();
// Disable caching this page (PHP)
header ("Cache-Control: must-revalidate, pre-check=0, post-check=0");
header ("Content-Type: application/binary");
header ("Content-Length: " . filesize($theFile));
header ("Content-Disposition: attachment; filename=dlimg.png");
readfile($theFile);
ob_end_flush();

In C# (ASP.NET) it’s just as simple:

private void Page_Load(object sender, System.EventArgs e)
{
  // Disable caching this page (C#)
  Response.Cache.SetCacheability(HttpCacheability.NoCache);
  Response.Buffer = true;
  Response.ContentType = "application/binary";
  Response.AppendHeader("Content-Disposition: attachment; " +
    filename=dlimg.png");
  Response.WriteFile(Server.MapPath("images/dlimg.png");
  Response.End();
}

In ASP:

FilePath = Server.MapPath("images/dlimg.png")

'Disable caching this page (ASP)
Response.CacheControl = "no-cache"
Response.Buffer = True

Set MyFSO = Server.CreateObject("Scripting.FileSystemObject")
Set MyFile = MyFSO.GetFile(FilePath)

if Response.IsClientConnected then
  Set MyStream = MyFile.OpenAsTextStream (1,-1)
  Response.ContentType = "application/binary"
  Response.AddHeader "Content-Disposition",
    "attachment; filename=dlimg.png"
  Response.Flush

  do
    Response.BinaryWrite MyStream.Read(1024000/2)
    Response.Flush
    if not Response.IsClientConnected then
      Exit Do
    end if
  loop until MyStream.AtEndOfStream

  MyStream.Close
  set MyStream = nothing
end if

Set MyFile = nothing
Set MyFSO = nothing

You could also use application/octet-stream instead of application/binary.

Technorati Tags , ,


One Comment so far...

david Says:

6 October 2005 at 1:05 am.

thanks!!!!!!

great post man!

Leave a Reply

Browse

Photography

Projects

Pages

Calendar

June 2005
M T W T F S S
« May   Jul »
 12345
6789101112
13141516171819
20212223242526
27282930  

Categories

www.flickr.com

Use OpenDNS