【发布时间】:2015-01-18 19:49:58
【问题描述】:
我有这个代码 sn-p 我在这里找到的:How to make PDF file downloadable in HTML link?
我尝试更改它,因为我的 PDF 文件位于“资源”目录中。
我以为我做对了,但它不起作用。
谁能解释我做错了什么?
<?php
if (isset($_GET["file"]) && !empty($_GET["file"])) {
$file = $_GET["file"];
$path = "/resources/";
$getFile = $path.$file;
if (file_exists($getFile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($getFile)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($getFile));
ob_clean();
flush();
readfile($getFile);
exit;
}
}
?>
我添加了 isset 部分,因为没有它,如果没有设置变量,则会引发错误。
这很好,但是当我添加 $path = "/resources/";和 $getFile = $path.$file;它什么也没做(也没有错误)。
编辑:什么不起作用?文件未下载。
测试于:Internet Explorer 和 Google Chrome。
编辑 2:我页面上的链接如下所示:
<a href="?file=kansasHandbook.pdf">Download PDF File</a>
【问题讨论】:
-
什么是不起作用?
-
文件未下载。在 IE 和 Chrome 中测试。
-
更新了我的问题。
-
您确定路径是
/resources/并且与您的 Web 根目录无关吗? -
非常确定。我所有的 PDF 文件都在 localhost/design/resources