HTML5 Download Attribute

In this tutorial we are going to look into another HTML5 feature with the download attribute.

The download attribute is a way of telling the browser that to download the file it is linking to, this can be a media file or a PDF document or a webpage etc. This is something you used to have to do with a server-side code. For example you will link to a server-side file of force-download.php and pass in an argument of the file you want to download.

<a href="force-download.php?file=download-webpage.html">Download Webpage HTML</a>

Then on the server-side you will have to get the contents of the the requested file and force the browser to download the contents by doing something like this.

function downloadFile($file){
    $file_name = $file;
    $mime = 'application/force-download';
    header('Pragma: public'); 	// required
    header('Expires: 0');		// no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');

Now we can avoid this step and just use the download attribute in the link.

<a href="download-webpage.html" download>Download Webpage HTML</a>

The download attribute isn't currently supported by all browsers currently only Chrome, Firefox and Opera support the attribute the other browsers will treat this just link any other link. Therefore it will just open the document or media file up in the browser, but with browsers that support this new attribute will download the file you are linking to on the user's machine.

To view an up to date version of the current support browsers of the download attribute you can view it on the link below.

Browser Support For Download Attribute

The download attribute is great to use on things like a PDF document if you want people to have this as a hardcopy for something, like a receipt. Instead of just opening it up in the browser you can make the user download it directly.

You can even change the name of the file you are downloading by adding a value to the download attribute like the following example.

<a href="some-random-generated-filename.pdf" download="invoice.pdf">Download Invoice</a>
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days