How to create a link that triggers file download?

13,402

Solution 1

If you're on Apache, you can drop this into your .htaccess:

<Files *.pdf>
  Header set Content-Disposition attachment
</Files>

This will send all PDF documents as downloads. mod_headers has to be enabled though.

Solution 2

Redirect to a PHP page with this code on it:

<?php
header('Content-disposition: attachment; filename=movie.mpg');
header('Content-type: video/mpeg');
readfile('movie.mpg');
?>

your <a href code will need to point to a specific page, and readfile will call your resource

Further reading

Just as a side note, I do agree that you should not override a browsers settings, but sometimes when the boss asks, you just have to do.

Solution 3

You can also use the following code:

<?php 
$file = filter_input(INPUT_GET, 'file');
$filename = basename($file);
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"{$filename}\";");
readfile("your file path {$file}");
?>

This will prompt any file extensions such as (.pdf,.docx,.zip,.csv,.txt,.html,.php and so on...) without directly opening into the new browser.

Solution 4

You can force the browser to save the linked content by adding an HTTP header to the web server response:

Content-Disposition: attachment; filename=<default filename to save as>

On the other side, I don't really see the point in overriding the user's browser configuration, which usually tells if PDF documents should per default be opened in the browser, opened in a separate PDF viewer or saved to disk.

Solution 5

You can use the HTML5 download attribute on your a tag.

<a href="http://love4cats.com/kitten-catalogue.pdf" download>Download the CATalogue</a>

You should check your analytics and make sure that your target browser supports the attribute. See the caniuse.com entry page for browser support.

Share:
13,402
edt
Author by

edt

Updated on July 31, 2022

Comments

  • edt
    edt almost 2 years

    When a user clicks a "Download PDF" link, I would like for the download prompt to appear and for the user to be able to download the file.

    Currently, the user is just transferred to the address of the PDF file.

    For example:

    <a..[what goes here??]..>Download PDF</a>
    

    It seems that there's a combination of JavaScript & PHP needed to do this.

    Can anyone give an example?

  • Roger Lipscombe
    Roger Lipscombe over 13 years
    While I agree, in general, that the user's preference should be honoured, I can think of at least one case where they should be encouraged to download the file, rather than view it in the browser: situations where they probably ought to save a copy, such as on-line insurance policies, or similar.
  • Darkwater
    Darkwater over 11 years
    There is also a download attribute. (Not sure which browsers support this, but you could add it anyway.)