4

我正在尝试放置一个链接以从服务器下载 pdf,而不是重定向浏览器以在另一个页面中打开 pdf。我在许多网站上都看到过这样的选项,但无法获取代码。大多数人都说应该只使用 php,任何人都可以帮助我。

4

4 回答 4

5

使用以下代码将其重定向到 php 页面:

$path_to_file = '/var/www/somefile.pdf'; //Path to file you want downloaded
$file_name = "somefile.pdf"; //Name of file for download
header('Pragma: public');   // required
header('Expires: 0');    // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
readfile($path_to_file);
die();
于 2012-09-24T13:10:58.627 回答
3

或者您可以将其包含在.htaccess

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>
于 2012-09-24T13:09:19.773 回答
0

来自 php

    header("Content-Type: application/octet-stream");
    header("Content-Disposition:attachment;filename=myfile.pdf");

然后是文件内容

或来自 Apache

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>
于 2012-09-24T13:11:59.640 回答
0

您有时可以更改 http 标头:

header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"lol.pdf\"");  

像这样。但是出于安全原因,某些浏览器实际上会阻止此操作。

编辑

因为我意识到它并不清楚。这些标头将从另一个页面发送,该页面实际读取文件并将其与这些标头一起发送到浏览器。

然后,该链接会将其href属性指向该 PHP 页面,该页面读取文件并发送标头。

于 2012-09-24T13:10:12.590 回答