How to force PDF to download beginner [duplicate]

2019-01-24 17:07发布

问题:

Possible Duplicate:
How to force a pdf download automatically?

I've checked other forums, but I do not understand what they say. I've checked this link which people do seem to get the solution:

http://css-tricks.com/snippets/htaccess/force-files-to-download-not-open-in-browser/

I want to do a button which is done for downloading a PDF, the file is too big to see it online. So I want that button to force the browser to download the file. Asking or not asking the user. There will be different PDF name files so I need to make this button downloadable with PDF formats of various PDF files.

I've checked different webs and it seems it can be done using htaccess, but I honestly have no clue of how to do this. Can somebody help to show me how I can do this!?!?! Is there a simple way via CSS/html??

I've been stuck for a long while for such a small detail.

My code is simply:

<div class="Container for icons">
<a href="hugefile.pdf" alt=""><img href="icon.png" alt=""/>
</div>

Could somebody give me hand on this one?

回答1:

You'll need to modify the HTTP header returned to the client in order to accomplish this:

  • Force to open "Save As..." popup open at text link click for pdf in HTML

Here's a PHP code example:

$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // For download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change this mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);  //this is necessary in order to get it to actually download the file, otherwise it will be 0Kb


回答2:

Instead of AddType you could try ForceType:

<FilesMatch "\.(pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>