2012-08-16 146 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