Force a file to download when link is clicked

So here’s a simple snippet for when you want to force a download of a file (such as a PDF, .doc etc), when a link is clicked.

The default action will open the document in the either the same browser window, or in a new tab/window by using the usual target methods:

Open file in same window:

<a href="myfile.pdf" target="_self">Click to Download</a>

Open file in new window:

<a href="myfile.pdf" target="_blank">Click to Download</a>

 

However, if you want to force the file to download, by prompting a download pop-up box (to open or save), then all you need to do is add ‘download’ to the <a> link as seen below:

Force file download window:

<a href="myfile.pdf" download>Click to Download</a>

EDIT: There appears to be a new method now which may work more consistenly across all browsers:

<a href="myfile.pdf" download="myfile.pdf">Click to Download</a>

 

Voila! Hope this helps.

Useful post? Share it

6 comments on “Force a file to download when link is clicked

  1. Thanks Phil…. so simple and elegant – who would have imagined?

    I’m trying to use it to force a download of an mp3.
    The ‘force file download’ code works perfectly in Chrome, but in Safari & Firefox, it opens the file in a new window.
    Any ideas on how to have Safari & Firefox download the mp3 instead of opening it in a window?
    Thanks in advance.

  2. It works for me in Firefox, Chrome, and Opera. Unfortunately it is not working in Safari, but rather only opens the file in a new tab. Is this one of those compatibility issues that will eventually be resolved? And whether or not, is there anything else that we can do in the meantime without having to write dedicated scripts?
    Thanks for the info.

  3. If you want a downloadable file type on you whole site, just add this to your .htaccess:

    Header set Content-Disposition attachment

Leave a Reply

Your email address will not be published.