2012-08-16 89 views
3

可能重复:
How to force a pdf download automatically?如何强制PDF下载初学者

我检查了其他论坛,但我不明白他们在说什么。我检查这个链接,人们似乎得到了解决方案:

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

我想要做的这是用于下载PDF做一个按钮,该文件是太大,在网上​​看到它。所以我想要那个按钮来强制浏览器下载文件。询问或不询问用户。会有不同的PDF名称文件,所以我需要使用各种PDF文件的PDF格式下载此按钮。

我检查过不同的网站,它似乎可以使用htaccess完成,但我真的不知道如何做到这一点。有人可以帮助告诉我怎样才能做到这一点!?!?!有没有简单的方法通过CSS/HTML?

我一直坚持了很长一段时间这样一个小细节。

我的代码很简单:

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

可能有人给我的手在这一个?

+0

使用PHP更有效。 – Homework 2012-08-16 15:50:26

回答

10

你需要修改返回给客户端的HTTP标头,以实现这一点:

下面是一个PHP代码示例:

$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 
5

相反AddType你可以试试ForceType

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

注意:这是一个Apache配置 – paulsm4 2012-08-16 18:02:14