Download Files

Server-based Downloads

Currently, the best solution for giving your users the ability to download a file is by setting the HTTP headers. With PHP, you would do it as follows.

<?PHP
// Define the path to file

$file = $_GET['fileName'];
echo ("<p>$file</p>");

if(!file) {
	// File doesn't exist, output error
	die('file not found');
} else {
	// Set headers
	header("Cache-Control: public");
	header("Content-Description: File Transfer");
	header("Content-Disposition: attachment; filename=$file");
	header("Content-Type: application/msword");
	header("Content-Transfer-Encoding: binary");
	header('Expires: 0');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Pragma: public');
	header('Content-Length: ' . filesize($file));
	ob_clean();
	flush();
	// Read the file from disk
	readfile($file);
}
?>

Usage

For example, let's say the above code has been saved to a file called “download.php”. If you want your users to download a file called “myDoc.docx”, then you could something like:

<a href="download.php?fileName=myDoc.docx">Download Now</a>

Server-less Downloads

The download attribute gives your users the ability to download a file from your webpage, or perhaps the app cache. For example:

<a href="../images/marbleBricks.jpg" download="Marble-Bricks.jpg">

Click the marble bricks to download the high-resolution image.

Compatibility Warning (not ready for prime time)

Check for Support

As of this writing, the only browser that supports this attribute is Chrome, then only dev channel release (14.0.835.15+). The other major drawback is that it currently will not work if the html document opened with local file protocol. I am sure we will see wider support soon as it is already in the WHATWG spec.

"The download attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default filename that the author recommends for use in labeling the resource in a local file system. There are no restrictions on allowed values, but authors are cautioned that most file systems have limitations with regard to what punctuation is supported in file names, and user agents are likely to adjust file names accordingly." WHATWG a[download] description